0

I have some div with its click actions and another div inside first - 'close-cross' on right-top corner witch close the first one or wherever else.

Problem is that when close-cross div is clicked, the main div click action is called too. Theoretically both are clicked, because the mouse button was pressed, and mouse pointer was above both divs, but I want only the div that is clicked directly to call its click event.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Can you please post your html/javascript code? – Vikram Oct 02 '12 at 15:48
  • I *think* I understand what you're asking, but putting together a fiddle or showing some markup would be more helpful in understanding what you're getting at. – kinakuta Oct 02 '12 at 15:49

4 Answers4

1

You want to use the event.stopPropagation() method. This prevents events bubbling up the DOM tree. See the jQuery documentation here

Josh
  • 1,794
  • 3
  • 17
  • 31
1

In the close function you'll want to call event.stopPropagation()

http://api.jquery.com/event.stopPropagation/

This will prevent the event from bubbling up to the parent div. More on event bubbling:

What is event bubbling and capturing?

Community
  • 1
  • 1
jholloman
  • 1,959
  • 14
  • 16
1

Event Bubbling, is what this is called, and it can be checked using this:

$(document).ready(function() {
$('#main').click(function(event) {
if (event.target == this) {
//Your code here
}
});
});

the event.stopPropagation(); stops journey of the event

$(document).ready(function() {
    $('#close-cross').click(function(event) {

    //Your code here
   event.stopPropagation();
    });
    });
geekman
  • 2,224
  • 13
  • 17
0

Check this FIDDLE

$(document).ready(function() {
     // Outer Div click Event
    $('div.a').on('click', function(e) {
        if (e.target.className === 'b') {
            e.preventDefault();
        }
        else {
            alert('Outer Div Clicked !!');

        }
    });

    // Inner Div Click event
    $('div.b').on('click', function(e) {
        alert('Inner Div Clicked !!');
    });
});​
Sushanth --
  • 55,259
  • 9
  • 66
  • 105