To access the event object, include an event
parameter in the event listener callback function:
var foo = document.getElementById("foo");
foo.addEventListener("click", onClick);
function onClick(event) {
// the `event` parameter is the event object
// e.g. `event.type` would be "click" in this case
};
e.stopPropagation();
HTML:
<div id="parent">
<div id="child"></div>
</div>
Javascript:
var parent = document.querySelector('#parent');
var child = document.querySelector('#child');
child.addEventListener('click', function(e) {
e.stopPropagation();
alert('child clicked!');
});
parent.addEventListener('click', function(e) {
alert('parent clicked!');
});
since the child stops the event propagation, and the events are listened to during bubbling phase, clicking on the child will only trigger the child. without stopping the propagation both events will be triggered.
e.preventDefault();
The event.preventDefault()
method stops the default action of an element from happening.
For example:
var allAnchorTags = document.querySelector('a');
allAnchorTags.addEventListener('click', function(e){
e.preventDefault();
console.log('anchor tags are useless now! *evil laugh*');
});
e.target vs e.currentTarget
e.currentTarget Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.
in other words
e.target
will return what triggers the event dispatcher to trigger
e.currentTarget
will return what you assigned your listener to.
HTML:
<body>
<button id="my-button"></button>
</body>
Javascript:
var body = document.body;
body.addEventListener( 'click', function(e) {
console.log('e.target', e.target);
console.log('e.currentTarget', e.currentTarget);
});
if you click my-button
,
my-button
body