0

Possible Duplicate:
Prevent parent container click event from firing when hyperlink clicked

I have

<div onClick="someJScode();">
  ...
  <div></div>
  ...
</div>

I don't want someJScode() to be called when the inner div is clicked. How to do this?

Community
  • 1
  • 1
burtek
  • 2,576
  • 7
  • 29
  • 37

2 Answers2

6

$('yourinnerDiv').click(function(e){e.stopPropagation()});

This will stop click event bubbling up the DOM.
http://api.jquery.com/event.stopPropagation/
https://developer.mozilla.org/en/docs/DOM/event.stopPropagation

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
Dharman
  • 30,962
  • 25
  • 85
  • 135
3

You can try this:

HTML

<div onClick="someJScode();" class="parent">
  <div class="child" onclick="childCallback(event)"></div>
</div>

JavaScript

function someJScode() {
    alert('Click!');
}

function childCallback(event) {
    event.stopImmediatePropagation();
    return false;
}

DEMO

The code above uses stopImmediatePropagation You can also use stopPropagation

Here is more generic solution:

var preventChildrenPropagation = (function (parentClass) {
    var preventPropagation = function (event) {
        event.stopPropagation();
        return false;
    }
    return function (parent) {
        var foreach = Array.prototype.forEach;
        foreach.call(document.getElementsByClassName(parent), function (e) {
            foreach.call(e.children, function (c) {
                c.onclick = preventPropagation;
            });
        });
    }
}());

preventChildrenPropagation('parent');

The method preventChildrenPropagation will prevent the propagation of all click events of all children of the "parent" element.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68