Hello there,
I have been working in the book by Kirupa Chinnathambi (JavaScript: absolute beginner’s guide, chapter 11, console logging basics), and have a question regarding this piece of code below. I am thinking that argument “e” is the button, but I am not sure. Thanks for your help!
Note: doSomething is referenced here:
myButton.addEventListener("click", doSomething, false);
function doSomething(e) {
counter++;
//console.log("We clicked on " + e.target.id);
console.log("Button clicked " + counter + " times");
if (counter == 3) {
showMore();
}
}
e
represents the Event object. Event objects are passed into functions used as event handlers when given to addEventListener()
. Depending on what kind of event it is, it could have different properties associated with it. Common kinds of event objects are MouseEvent objects and KeyboardEvent objects. You can find more about them here:
The button itself is represented by e.target
using the target
property of the Event object. This is the element that triggered the event in the first place. Another common property is the e.currentTarget
property which is the element addEventListener()
was called from (in this case myButton
). Note that these may not always be the same. Because events bubble, elements deeper in the hierarchy may trigger an event that get picked up by listeners higher in the hierarchy. In that case, target and currentTarget would be different. Here, since the button has no child elements of its own, both target and currentTarget in the Event object will both refer to the button element.
console.log(e.target === myButton); // true
2 Likes