Joel Worsham
Joel Worsham

Reputation: 1150

Jquery wrong event

So I have an interesting problem.

I have this html code (pardon the inline styling, it works best for the website):

<div id="videopage">
<div class="videoframe" source="http://www.youtube.com/embed/8Kb6xcyclPU?rel=0" style="float:left;width:135px;height:101px;border:5px solid #555;border-radius:5px;position:relative;background:#555555;">
<img style="position:absolute;cursor:pointer;" src="/wp-content/themes/casterconcepts/images/vid-thumbs/casters-and-wheels.jpg" /><div class="close" style="width: 40px;height: 40px;border-radius: 20px;background: #9b9b9b;opacity: 0.5;position: absolute;bottom: -20px;right: -20px;color: white;text-align: center;line-height: 38px;font-size: 35px;opacity:0;display:none;cursor:pointer;">&#10006;</div>
</div>
</div>

And this javascript code:

$(function(){
  $("#videopage .videoframe").click(function(){
    var source = $(this).attr("source");
    $(this).children("img").animate({opacity:0},300)
    .parent().delay(500).animate({width:"400px",height:"300px"},500).append('<iframe style="opacity:0;" width="400" height="300" src="'+source+'" frameborder="0" allowfullscreen="" ></iframe>')
    .children("iframe").delay(1300).animate({opacity:1},500)
    .parent().children(".close").delay(1800).css("display","block").animate({opacity:0.5},300);
    alert("open event");
  });

  $("#videopage .close").hover(function(){
    $(this).stop().animate({opacity:0.8},150);
  },function(){
    $(this).stop().animate({opacity:0.5},150);
  });

  $("#videopage .close").click(function(){
    alert("close event");
    $(this).animate({opacity:0},{duration:300,complete:function(){
      $(this).css("display","none");
      }
    });
  });
});

jsFiddle Here

Essentially, when you click the div, the video opens up and everything is fine. The "first" event is fired.

The problem is, when you click the close button and try to fire the "second" event, the "first" event is ALSO fired.

So when clicking the close button and the jquery event with the selector "#videopage .close" is fired, the event "#videopage .videoframe" is ALSO fired.

This should not be. The only event being fired when clicking the close button is the "#videopage .close".

Any ideas why?

Upvotes: 1

Views: 93

Answers (1)

Guffa
Guffa

Reputation: 700262

Events bubble, unless you keep them from doing so. Use the stopPropagation method to keep the click event from bubbling up to the parent:

$("#videopage .close").click(function(e){
  e.stopPropagation();
  alert("close event");
  $(this).animate({opacity:0},{duration:300,complete:function(){
      $(this).css("display","none");
    }
  });
});

Upvotes: 2

Related Questions