Detect click with pure JavaScript

With a library under the belt, events like click are a no brainer, with vanilla JavaScript things aren't chewed ready as much.

This is more one of those “note to self posts” as I learn vanilla JavaScript. Hopefully there’s help to other internet surfers also.

I have successfully managed to use two methods in detecting click events on a page.


var el = document.getElementById('module');

el.onclick = function() {
    console.log('Click just happened');

Or with an external function:

var el = document.getElementById('module'),
    clickerFn = function() {
        console.log('Click just happened');

el.onclick = clickerFn;

This method is very browser compliant, works in IE8 also.


var el = document.getElementById('module')
    clickerFn = function() {
    console.log('Click just happened');

el.addEventListener('click', clickerFn);

This wont work in IE8. But other event’s can be binded to it also.

Click on a NodeList

getElementById() only gets one element, and onclick can listen that element. But what if getElementsByClassName() or getElementsByTagName() is used, since multiple elements can have the same class, or be the same tag, it’ll return a NodeList and we need to iterate it over with a for loop:

var el = getElementsByClassName('module');
for (var i=0; i < el.length; i++) {
    // Here we have the same onclick
    el.item(i).onclick = clickerFn;


Way more looping in pure JavaScript than when using a library. If you have trick in your sleeve, please do share it in the comments.


Club-Mate, the beverage →