Zaki Aziz
Zaki Aziz

Reputation: 3852

jquery: Prevent some child elements from executing the called event

First of all I want to link you guys to the JSFiddle I've made that replicates my issue: http://jsfiddle.net/E7sLA/

What I want to do is have a class called .b show when the parent list item element is clicked. So the text inside of <div class="b"> </div> should be shown when ever a user clicks anywhere in the parent list item element. That part of my script is working properly, the part that isn't working (or rather what I'm trying to achieve) is when a user clicks on a link inside the list item I do not want the content inside of <div class="b"> </div> to expand. I want the user to be redirected to where ever the link leads to.

My page looks something like this:

<div id="x">
    <ul>
        <li>
            <div class="a">
                <a href="http://cnn.com">some link</a> click here to expand
            </div>
            <div class="b">
                <input type="submit" value="Accept" name="accept"> 
                <input type="submit" value="Counter" name="counter"> 
                <input type="submit" value="Reject" name="reject">
            </div>
        </li>
        <li>
            <div class="a">
                <a href="http://yahoo.com">some link</a> click here to expand
            </div>
            <div class="b">
                <input type="submit" value="Accept" name="accept"> 
                <input type="submit" value="Counter" name="counter"> 
                <input type="submit" value="Reject" name="reject">
            </div>
        </li>
    </ul>
</div>

And this is the JQuery I'm running trying to acheive this effect:

$("#x li").click(function(e) {
    $(this).find(".b").slideToggle();
    $("#x a").click(function() {
        e.preventDefault();
    });
});

Upvotes: 1

Views: 449

Answers (3)

liunian
liunian

Reputation: 440

try this:

if the target is a link, do not toggle but just return

$("#x li").click(function(e) {
    if(e.target.tagName.toLowerCase() == 'a') return ;
    $(this).find(".b").slideToggle();
});

Upvotes: 1

Ariel Popovsky
Ariel Popovsky

Reputation: 4875

Try this:

 $("#x li").click(function(e) {
    $(this).find(".b").slideToggle();    
});
$("#x a").click(function(e) {
        e.stopPropagation();
});

Upvotes: 1

Robin Pyon
Robin Pyon

Reputation: 759

Is this the effect you're after? http://jsfiddle.net/m7HLM/

$("#x li").click(function(e) {
    $(this).find(".b").slideToggle(); 
});

$("#x li .b input").click(function(e){
    alert($(this).parents('li').attr('id') + " : " + $(this).attr('name')); 

    e.stopPropagation();   
});

e.stopPropagation() will prevent click events from bubbling up the DOM tree, and stops the <li> element from closing when you click something nested inside it.

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

Upvotes: 0

Related Questions