Reputation: 12096
I am trying to create a small 20x20px div box, that when clicked opens a 200x200px box located inside the first box:
HTML
<div id="container" style="width:20px; height:20px;">
<div id="box" style="display:none;width:200px; height:200px;">
<img src="example1.gif" />
<img src="example2.gif" />
</div>
</div>
Aim
My aim is to make it so when #container
is clicked, #box
is faded in. The user will then click an image inside this box and the #box
will then fade out.
#container
clicked and #box
fadeIn();
#box
is clicked#box
fadeOut()
To do this I am using the following jQuery:
$(document).on("click", "#container", function(){
$("#box").fadeIn("fast");
});
$(document).on("mouseleave", "#box", function(){
$("#box").fadeOut("fast");
});
$(document).on("click", "#box img", function(){
// Do things, removed for example
$("#box").fadeOut();
});
What actually happens
At the moment it's not working though because this happens:
#container
#box
fades in#box img
#box
fades out#box
fades inNumber 6. on the above list should not happen, the box should not fade back in.
I think the problem is with .on("click", "#container", function(){
this may be applying that code when #container #box img
is clicked, how can I stop this?
Demo
Upvotes: 1
Views: 224
Reputation: 33661
You need to use event.stopPropagation(). The event is bubbling up which is causing the div to fade in again.
$(document).on("click", "#box img", function(e){
e.stopPropagation();
// Do things, removed for example
$("#box").fadeOut();
});
Upvotes: 3
Reputation: 196002
Change your last part to use event.stopPropagation
so that the event does not bubble up to the #box
element.
$(document).on("click", "#box img", function(e){
// Do things, removed for example
e.stopPropagation();
$("#box").fadeOut();
});
Upvotes: 2