0
votes

How do i prevent the parent click event from firing if the child div is clicked?

http://jsfiddle.net/2GEKu/

var p = document.getElementById('parent');
var c = document.getElementById('child');

p.onclick = function () {
    alert('parent click');
}
c.onclick = function () {
    alert('child click');
}
1

1 Answers

3
votes

Invoke the .stopPropagation() method of the event object in the child's handler.

var p = document.getElementById('parent');
var c = document.getElementById('child');

p.onclick = function () {
    alert('parent click');
}
c.onclick = function (event) {
    event.stopPropagation();
    alert('child click');
}

To make it compatible with IE8 and lower, do this:

c.onclick = function (event) {
    if (event)
        event.stopPropagation();
    else
        window.event.cancelBubble = true;
    alert('child click');
}