views:

22

answers:

1

Hey.

I have a big DIV called #bigDiv. In this div I have other elements like menus and images.

I want jQuery to toggle the #bigDiv every time user clicks the #bigDiv NOT other elements (which are parts of this div). How to do this?

For example:

index.html:

<div id="bigDiv">
<ul>
<li><a href="site">Site</a></li>
</ul>

jQuery:

$("#bigDiv").click(
function{
$("#bigDiv').toggle();
});

$("li").click(
function{
//do something here
});

At this point when I click li elemnt it still closes the main div. I tried with z-index, but it doesn't work since element is still a child of the main div.

Thanks.

+3  A: 

You can prevent the event from bubbling up, by using stopPropagation():

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

$("li").click(function(event){
    event.stopPropagation();
    //do something here
});

Alternatively, you could test which element is clicked in the event handler of bigDiv:

$("#bigDiv").click(function(event){
    var tar;
    if (event.target) targ = event.target;
    else if (event.srcElement) targ = event.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if(targ.id == 'bigDiv')
        $("#bigDiv').toggle();
});

Also worth reading: quirksmode - Introduction to Events and quirksmode - Event properties

Felix Kling