#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2004
    Posts
    86
    Rep Power
    11

    How to set onclick event of a link in script?


    Why cant i set the onclick event of a link in javascript?

    No errors but does not work:

    if (document.all[i].tagName == "A"){
    document.all[i].onclick = "myfunction();";
    }

    Object does not support this property or method:
    document.all[i].addEventListener("click", "myfunction();", true);

    But i can set the .href with no problem and it works.

    So how can i set the onclick event in script?
    Please dont reply to say to use something like <a onclick=""> i want to do it in code not in html!
  2. #2
  3. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,124
    Rep Power
    4303
    Don't use document.all. It's obsolete. Use DOM1+ methods, like document.getElementById() and document.getElementsByTagName(), instead.

    Your other problem is that functions aren't strings.

    Code:
    someElement.onclick = myfunction;
    OR
    Code:
    someElement.onclick = function() {
      myfunction();
    }
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).

IMN logo majestic logo threadwatch logo seochat tools logo