I am trying to understand the differences between passing ‘this’ to a function versus passing a reference to the event itself.
I am testing with two separate divs and each has a separate function for mouseover and mouseout events. I pass just ‘this’ to one function and I pass both ‘this’ and ‘e’ to the other. My example is here: http://jsfiddle.net/jkolden/NQvaL/13/
document.getElementById('output').onmouseover = function(e) {mousein(e, this);}; document.getElementById('myDiv').onmouseover = function() {mouseinAlt(this);};
It seems as though the ‘this’ keyword is always going to refer to the html element to which I attach my listener, but ‘e’ will refer to the child of that html element is being moused over; is that a correct statement? I’m just curious if I am understanding this properly and if my example is using these in an appropriate manner.
Advertisement
Answer
this
refers to the element to which you attached the event. e
refers to the event object. Within that event object is a reference to the event’s target
(not always the same property in every browser, in IE it’s srcElement
), which is the element on which the event was dispatched.
See more here: https://developer.mozilla.org/en-US/docs/Web/API/event.target