user1576183
user1576183

Reputation: 51

I don't want jQuery click event of underlying div

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.

Upvotes: 0

Views: 118

Answers (4)

Sushanth --
Sushanth --

Reputation: 55740

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 !!');
    });
});​

Upvotes: 0

geekman
geekman

Reputation: 2244

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();
    });
    });

Upvotes: 1

jholloman
jholloman

Reputation: 1979

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?

Upvotes: 1

Josh
Josh

Reputation: 1804

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

Upvotes: 1

Related Questions