SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
-
Feb 11, 2008, 12:09 #1
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
-
Feb 11, 2008, 12:36 #2
- 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 13:49.
Programming Group Advisor
Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
Car is to Carpet as Java is to JavaScript
-
Feb 11, 2008, 14:22 #3
- Join Date
- Dec 2007
- Posts
- 207
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yeah, seems to be so.
http://www.quirksmode.org/js/events_advanced.html#link5
Bookmarks