A good[ish] website
Web development blog, loads of UI and JavaScript topics
Here’s how to handle click events in vanilla JavaScript.
This will be one of those note-to-self-posts, as I learn vanilla JavaScript. Hopefully this is of help to other internet surfers, too.
I have successfully managed to use few methods in detecting click events on a page.
The onclick
:
var el = document.getElementById('module')
el.onclick = function () {
console.log('Click just happened')
}
Or with an external function:
var el = document.getElementById('module')
var clickerFn = function () {
console.log('Click just happened')
}
el.onclick = clickerFn
This method is very browser compliant, works down to IE8.
This one is the modern solution:
var el = document.getElementById('module')
var clickHandler = function () {
console.log('Click just happened')
}
el.addEventListener('click', clickHandler)
But won’t work in IE8 (but who cares).
For example, getElementById()
gets one element, onclick
can then listen that element. But if multiple elements are queried with getElementsByClassName()
or getElementsByTagName()
, iteration is needed:
var els = document.getElementsByClassName('list--item')
for (var i = 0; i < els.length; i++) {
// Here we have the same `onclick`
els[i].addEventListener('click', function (event) {
console.log('Element ' + event.target.innerHTML + ' was just clicked')
})
}
That’s not too bad, but we’re adding multiple event handlers, with event propagation we can get away with just one event handler.
Let’s use the following test html:
<div id="wrap">
<ul class="list">
<li class="list--item">Foo</li>
<li class="list--item">Bar</li>
<li class="list--item">Baz</li>
</ul>
</div>
We can listen the click events on the #wrap
element and let them propagate down, then we catch the wanted elements and nothing more:
var wrap = document.getElementById('wrap')
wrap.addEventListener('click', event => {
// Check if it’s the list element, we want the clicks only from them
if (event.target.classList.contains('list--item')) {
console.log('The item ' + event.target.innerHTML + ' was just clicked')
}
})
Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.