We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

noah on 04/30/07


Tagged

DOM click events ui eventhandlers onclick quirksmodeorg ppk


Versions (?)


Who likes this?

7 people have marked this snippet as a favorite

tylerhall
inamorix
vali29
heinz1959
SpinZ
korzhik
hans


Which element was clicked?


Published in: JavaScript 


How to get a reference to the element that was clicked to fire an event. The code is gratefully cribbed from Quirksmode.org.

Updated to reflect how I actually implement this, slightly different from PPK's original.

  1. <html>
  2. <head>
  3. <script>
  4. /* http://quirksmode.org */
  5. function getEvent (e) {
  6. var event = e || window.event;
  7. if( ! event.target ) {
  8. event.target = event.srcElement
  9. }
  10. return event;
  11. }
  12. </script>
  13.  
  14. </head>
  15. <body>
  16. <a href="#fred" id="fred" onclick="alert(getEvent(event).target)">foo</a>
  17. </body>
  18. </html>

Report this snippet 

You need to login to post a comment.