This article will show you how to differentiate click on a div and a click on one of it’s children.
TL;DR
$('.outer').on('click', function(event) { |
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:
$('.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.
$('.red').on('click', function(event) { |
Solution in vanilla JavaScript
Native JavaScript provides the same property, here is how to use it:
var redDiv = document.getElementById('red'); |
window.event is the IE way of retrieving the event information.