It’s always the best practice to shorten your JavaScript code, that’s why we often times move our repeated lines of code to a function (call it cooking), turning multiple lines of code into one. But what if we can shorten / cook our events as well? That is exactly what I’ll show you below – events with multiple selectors.
Note that this is not to be confused with the Breaking Bad, a popular show starring popular characters such as Heisenberg and Jesse Pinkman, in any way.
Our function will have 4 arguments
Parent
, Event
, Selector
, Handler
. Depending on your use case, you could just use document
instead of the Parent
argument, however I always prefer to stay flexible. Event
, as you might have already guessed, will be the 'click'
, 'hover'
, and etc. Selector
should become an array of strings (i.e. classes, ids, etc.), which is the main point of this cook. Handler
will be the function that’s called after our event has occurred. Here is a full code example (Parent
, Event
, Selector
, and Handler
will be shortened to first letter):
function addEvent(p, e, s, h) {
parent.addEventListener(e, function(evt) {
if (evt.target.matches(s + ', ' + s + ' *')) {
h.apply(evt.target.closest(s), arguments);
}
}, true);
}
Now the use example will look like this:
window.addEventListener("load", function(){
addEvent(document, 'click', '.my-awesome-class, #my-awesome-id, [src="my-awesome-other"]', function(evt) {
//stuff to do after clicking selectors
});
});
Do note that if your selector has quotation marks, then the selectors should be in between the single quotation marks, or the other way around.
What we observe is not nature itself, but nature exposed to our method of questioning. – Werner Heisenberg