views:

32

answers:

1

Possible Duplicate:
How to ignore click event when clicked on children.

I wanted to know how can i build <li> that is clickable with jQuery while inside it, I have <a href="/home"> that i don't want it to do the same as the click on the rest of the li do...

Example :

<li> <div> bla bla </div> <div> <a href="/home"> </a> </div> </li>

and the jQuery code :

$(document).ready(function() {
$('li').hide();

$("li").toggle(
function(){$(this).next().show("slow");},
function(){$(this).next().hide();}
);

});

Now i want the toggle function not to work on the <a href> only on the rest of the <li>, I explain, when I click on the link I want to reach "/home"...

Thanks, Golan

+1  A: 

The problem comes from the fact the click event happens on the a tag then bubbles up to happen on the list item, and any other elements that happen to be in that branch of the DOM.

The solution is to stop this bubbling in the click event on the link. Something like the following should work.

$('li a').click(
    function(event){
        event.cancelBubble = true;
        if (event.stopPropagation) event.stopPropagation();    
    }
);

You could just return false in the event above, but that would also stop the browser following the link.

laurencek