6

I am trying to add a click event on a div thats inside a li that already has a click event. I don't want the li click event to fire when the div click event is fired.

Here is the jsfiddle of what I am trying to do. http://jsfiddle.net/2srUd/5/

When I click on the .inside I don't want the #outside click to fire. I assume I need to ad a not to the selector $(".inside")

<script>
    $(document).ready(function() {

        $("#outside").click(function() {
            alert("outside click");
        });

        $(".inside").click(function() {
            alert("inside click");
        });

    });
</script>
<ul>
    <li id="outside" style="border:2px solid red; padding:20px;">
        <div class="inside" style="border:2px solid blue; ">Click This Div. I want to accept the inside click but not the outside click.</div>
    </li>
</ul>

2 Answers 2

15

Simple fix:

    $(".inside").click(function(e) {
        e.stopPropagation();
        alert("inside click");
    });

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

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

Basically you don't want it to fire the parent's event handler, so you stop the propagation.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me only the outside div ever generates the event. the only difference is that my outside div is a class name not an id if that changes anything <div class='outer'><div class='inner'>a</div><div class='inner'>b</div></div>
3

Just do: http://jsfiddle.net/2srUd/24/

$(document).ready(function() {
        $("#outside").click(function() {
            alert("outside click");
        });

        $(".inside").click(function() {  
            alert("inside click");
            return false;
        });

    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.