0

Let's say I got a simple click event for a HTML div. If I click on the div it should trigger a fadeToggle.

In that div I got another div with another trigger. On that click event it should do something but instead of doing the event it triggers the first event.

How do I prevent event 1 from triggering if I want event2 to trigger?

Event1 should trigger only if I don't press the clickevent on the second event everything else should trigger as usual.

Thanks for your time

HTML

<div id="1">
     Event 1
     <div id="2">
         <div id="3">
            but here is something as well event2
          </div>
     </div>
</div>

JavaScript

$("#1").click(function() {
   $(this).slideToggle();
});


$("#3").click(function() {
   $(this).css("background-color", "blue");
});

Fiddle: http://jsfiddle.net/VLcxJ/

4 Answers 4

2
$("#3").click(function(e) {
    e.stopPropagation();
    $(this).css("background-color", "blue");
});

After that, clicks on #3 won't reach #2 or #1

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

1 Comment

Thank you. helped me out, I can accept your answer in 11 minutes.
2

Use event.stopPropagation(); :

$("#e3").click(function(event) {
   event.stopPropagation();
   $(this).css("background-color", "blue");
});

See it working here : http://jsfiddle.net/bYn22/

Note from jQuery API (I couldn't explain it better) : event.stopPropagation() > Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

And note that your IDs can't begin with a number :)

1 Comment

It would be nice if you add an explanation of why he should be using event.stopPropagation(); Now your answer looks as : Add this code and it would work
0
$("#3").click(function(event) {
   event.stopPropagation();
   $(this).css("background-color", "blue");
});

Added Fiddle: http://jsfiddle.net/VLcxJ/1/

2 Comments

This is basically the same thing that I wrote :)
Of course, when I submitted the answer yours was no there yet on my browser, didn't meant to steal or anything.
-1

Here is the solution

        $("#1").click(function() {
            $(this).slideToggle();
        });


        $("#3").click(function(event) {
           event.stopPropagation();
            $(this).css("background-color", "blue");
        });

http://jsfiddle.net/tR7h9/3/

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.