Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on() stopPropagation not working?

I can't seem to get this to stop propagating..

  $(document).ready(function(){
      $("body").on("click","img.theater",function(event){ 
          event.stopPropagation();    
          $('.theater-wrapper').show();
      }); 

       // This shouldn't fire if I click inside of the div that's inside of the 
       // `.theater-wrapper`, which is called `.theater-container`, anything else it should.
       $(".theater-wrapper").click(function(event){
           $('.theater-wrapper').hide();
       }); 
  });

Refer this jsfiddle

like image 541
Dylan Cross Avatar asked Jan 24 '12 22:01

Dylan Cross


People also ask

What is event stopPropagation () in jquery?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How do you do event stopPropagation?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

What is the difference between stopPropagation and preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.

What does event stopPropagation () do chegg?

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


2 Answers

Since you are using on on the body element and not directly on img.theater the event is going to bubble up to body element and that is how it works.

In the course of event bubbling .theater-wrapper elements click event will be triggered so you are seeing it.

If you are not creating any dynamic elements then attach the click event handler directly on img.theater element.

$("img.theater").click(function(event){
    event.stopPropagation();    
    $('.theater-wrapper').show();
}); 

Alternatively you can check the target of the click event inside .theater-wrapper elements click handler and do nothing.

$(".theater-wrapper").click(function(event){
    if ($(event.target).is('img.theater')){
         event.stopPropagation();
         return;
    }
    $('.theater-wrapper').hide();
}); 
like image 153
ShankarSangoli Avatar answered Sep 21 '22 17:09

ShankarSangoli


The best way to do that is :

$(".theater-wrapper").click(function(event){
    if (!$(event.target).is('img.theater')){
        $('.theater-wrapper').hide();
    }
}); 

It's working for me with an accordion and checkbox

like image 21
Fassbender Avatar answered Sep 24 '22 17:09

Fassbender