47

How would you check to see which item was clicked in the document, given this code?

if ( document.addEventListener && document.attachEvent && document.fireEvent ) {
    document.attachEvent( "onclick", function() {
     // ...
    });
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Leila Hamon
  • 2,505
  • 7
  • 24
  • 32
  • 2
    Why are you using `attachEvent` when `addEventListener` is available? – Quentin Jul 31 '12 at 13:26
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4590122/how-to-reference-the-caller-object-this-using-attachevent – nicosantangelo Jul 31 '12 at 13:31
  • @Quentin This was from the Jquery source code, I don't know why they used these two together, anyone have an answer to Quentin's question? – Leila Hamon Jul 31 '12 at 16:32

1 Answers1

68
// using e.srcElement or event.srcElement

try this :) and see this http://www.quirksmode.org/js/events_advanced.html

if (document.addEventListener){
    document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
} else if (document.attachEvent) {    
    document.attachEvent("onclick", function(){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
}
blueiur
  • 1,447
  • 1
  • 11
  • 17
  • 1
    The OP wants to know which element was clicked at the time the event is fired, and your answer doesn't seem to do that. – apsillers Jul 31 '12 at 13:36
  • 14
    `srcElement` is old and mostly a microsoft implementation, I'd rather use `event.target` when available. `var target = event.target || event.srcElement;` [Reference](http://stackoverflow.com/a/5301667/1331430). [MDN](https://developer.mozilla.org/en/DOM/event.target). – Fabrício Matté Jul 31 '12 at 13:43
  • No problem, also the first listener handler (`addEventListener`)'s function should use `e.target` I guess, ugh now even my head is spinning with these hacks for older versions of IE. – Fabrício Matté Jul 31 '12 at 13:51
  • This may be a little redundant but should make it bulletproof: [Fiddle](http://jsfiddle.net/nVj8z/). Thankfully nowadays there's jQuery to take care of handlers binding.. – Fabrício Matté Jul 31 '12 at 14:00
  • 3
    `event` is undefined. Did you mean to write `function(event)` instead of `function(e)`? – OdraEncoded Aug 01 '14 at 23:42
  • `event` is not defined, it should be `function( event )` – Walid Ajaj Dec 15 '21 at 09:52
  • In the old IE browser, the 'event' object exists as a property of the global 'window' object. Therefore, when 'event' is called (if document.attachEvent exists), 'event' is defined in global namespace. – blueiur Dec 17 '21 at 09:46