Reputation: 706
Currently working on a piece of code written by someone else for event handling. there are parts of the code that I am unsure about and if possible would like to get an explanation of what it all means.
if (div.addEventListener) {
div.addEventListener("click", handleClick, false);
} else if (div.attachEvent) {
div.attachEvent("click", handleClick);
};
function handleClick(e) {
var evt = e || window.event;
var target;
if (evt.target) {
target = evt.target;
} else {
target = evt.srcElement;
}
alert("You clicked on " + target.id);
};
I understand that it is checking to see if there is an event occurring, but why does it addEventListener twice as well as attachEvent twice? Also why does one return a false value and the other does not?
I am unsure as to what the second part of code is doing altogether, any possible explanation? I know it is the code that is called once the event(s) occur.
Upvotes: 0
Views: 202
Reputation: 20445
"addEventListener" doesn't works in IE(older Versions), in IE(older Versions) "attachEvent" works, So here check is maintained that which function is available, so it would be used.
Upvotes: 2
Reputation: 37504
if (div.addEventListener) {
div.addEventListener("click", handleClick, false);
} else if (div.attachEvent) {
div.attachEvent("click", handleClick);
};
Only one of these will happen (it's an IF statement). It first checks if the browser supports addEventListener
.
The false
parameter it passes in is the useCapture
argument:
"The third, now optional, parameter in addEventListener is “useCapture”, which literally means fire the event at “capture” and not “bubble”. When an event is attached to an element, it will fire once the event has fully bubbled up to the document. However, if you set the useCapture flag to true, the event will fire on capture, and not wait for the event to fully bubble up the DOM tree." - from http://benhowdle.im/useCapture-demystified.html
The second part of the code is ran when the user clicks the DIV. It's again, checking to see if the browser supports certain event properties, to get the right element that was clicked.
Upvotes: 0
Reputation: 944430
why does it addEventListener twice as well as attachEvent twice?
It doesn't.
It tests to see if the property has a value, and if it does it calls the function stored in the property.
Also why does one return a false value and the pother does not?
Neither returns a false value. One has false
passed in as the third argument. They are different functions and don't work the same way.
Upvotes: 0