Events+Cheat+Sheet
Events+Cheat+Sheet
Events are of course an integral part of modern applications. With Events, you
can react to user actions and provide a reactive user experience.
With those methods and properties you can, for example, retrieve the target
of the event or change its default behavior (e.g. prevent it from propagating).
Event Handlers
Event Handlers are set up on the emitting element itself. For example you
could set up a click listener like this:
document.querySelector('#container1').onclick =
function(event) {…}
Notice that the event object gets passed. This event object is available on each
event you might listen to.
Event Listeners
The disadvantage of Event Handlers is, that you only may have one at a time.
But sometimes you need more than one listener.
This is where Event Listeners come into play. They are set up differently and
you may provide as many as you wish:
document.querySelector('#container1').addE ventListener('click', listener1);
document.querySelector('#container1').addE ventListener('click', listener1);
document.querySelector('#container1').addEventListen
er('click', listener1);
document.querySelector('#container2').addEventListen
er('click', listener2);
function listener1(event) {
console.log('Listener 1 here');
}
function listener2(event) {
console.log('Listener 2 here');
}
Event Listeners can of course also be removed
document.querySelector('#container2').removeEventLis
tener('click', listener2);
Event Behavior
Events have some default behaviors. One very important one, is, that they
propagate.
That’s best explained as an example: If you have to <div> elements which are
nested inside each other, then you might want to listen to clicks on the inner
one.
However, since Events propagate, a click on the inner one will also trigger all
click listeners on the outer one.
This might not be the behavior you want and you can stop this from happening
by calling stopPropagation() on the event object passed into the handler
function.
function listenerInner(event) {
event.stopPropagation();
}