A good[ish] website

Web development blog, loads of UI and JavaScript topics

Detect click with pure JavaScript

Filed under: JavaScript— Tagged with: event

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 good old onclick property is from the original ECMA Script spec (IE 4 times):

var el = document.getElementById('module')

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

Or as extracted to a helper method for convenience:

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

el.onclick = clickerFn

Listen click with addEventListener

This one is the modern solution:

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

el.addEventListener('click', clickHandler)

It won’t work in IE8 (who cares anymore though).

Detect click on a NodeList

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 ' + + ' 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.

Event propagation

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>

We can listen click events on the outer #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 ('list--item')) {
    console.log('The item ' + + ' was just clicked')

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!