SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot matches's Avatar
    Join Date
    Aug 2006
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    what is the best way to tell if an <a> element has a onclick event already attached

    I have a function that will add onclicks to <a> elements on my page but I don't want it to do it if the link all ready has a hard coded onclick attached already.

    How can I tell if a link has an onclick already hard coded in?

    Thanks for any help

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    There are several different ways of assigning onclick handlers, so there are just as many ways to find out if there's anything assigned.

    Here is some code to test things with.

    Code HTML4Strict:
    <a id="anchor" href="javascript:alert()" onclick="alert(); return false;">

    Code Javascript:
    var anchor = document.getElementById('anchor');
    // Attach other events
    anchor.onclick = alert();
    if (anchor.addEventListener) {
        anchor.addEventListener('click', alert, false);
    } else if (document.attachEvent) {
        anchor.attachEvent('onclick', alert);
    }
     
    // Find events
    if (anchor.match(/^javascript:/i)) {
        // The javascript pseudo-protocol has been used
    }
    if (anchor.getAttribute('onclick') > '') {
        // The onclick attribute has been used
    }
    if (anchor.onclick > '') {
        // The onclick event registration has been used
    }

    I don't think it's possible to easily determine if addEventListener and attachEvent have been used.
    Last edited by paul_wilkins; Feb 11, 2008 at 12:49.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by pmw57 View Post
    I don't think it's possible to easily determine if addEventListener and attachEvent have been used.
    Yeah, seems to be so.

    http://www.quirksmode.org/js/events_advanced.html#link5


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
  •