SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Jun 2005
    Posts
    436
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Set onclick function via javascript

    I have an element with the id "myelement"

    Through javascript, I need to assign an onclick event to "myelement"

    Onclick, I want to run the function called myFunction();

    I tried document.getElementById("myelement").onclick = myFunction() but that evaluates the function while getting parsed instead of waiting until the element gets clicked

    What do I need to do?

    Thanks,
    Colin

  2. #2
    SitePoint Wizard chris_fuel's Avatar
    Join Date
    May 2006
    Location
    Ventura, CA
    Posts
    2,751
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In this case you simply need to take out the (). That will reference to the function itself, not the result of the function.

  3. #3
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like to use a custom addEvent function so you can fire off multiple functions if need be. (So you won't have to remodify myFunction with another function call if you decide to add anything else)

    http://www.dustindiaz.com/rock-solid-addevent/

    var foo = document.getElementById('foo');
    addEvent(foo, 'click', myFunction);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •