Differentiate background and foreground div clicks

2016-06-13

This article will show you how to differentiate click on a div and a click on one of it’s children.

TL;DR

1
2
3
4
5
$('.outer').on('click', function(event) {
if (event.target !== this)
return;
// Your code
});

The issue

You want to respond to click events on the red div, but when you click the green div, the event is triggered as well.

Example:

1
$('.red').click(function() {console.log('click')});

will be executed with a click on the red and green divs.

Solution with jQuery

jQuery provides an event.target property that represents the element that was effectively clicked. By comparing it to the element with the click event attached, it is possible to know is the event is being triggered due to bubbling.

1
2
3
4
5
6
7
$('.red').on('click', function(event) {
// compare the element clicked (event.target) with the
// element that has the click attached (this)
if (event.target !== this)
return;
console.log('red div was clicked')
});

Solution in vanilla JavaScript

Native JavaScript provides the same property, here is how to use it:

1
2
3
4
5
6
7
var redDiv = document.getElementById('red');
redDiv.onclick = function (e) {
var ev = e || window.event;
if(e.target !== this)
return;
console.log('red div was clicked');
}

window.event is the IE way of retrieving the event information.