Dan
Dan

Reputation: 12096

jQuery on click but not on child click

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.

  1. #container clicked and #box fadeIn();
  2. Item in #box is clicked
  3. #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:

  1. Click #container
  2. #box fades in
  3. Click #box img
  4. // Do things, removed for example
  5. #box fades out
  6. #box fades in

Number 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

http://jsfiddle.net/8FuBD/

Upvotes: 1

Views: 224

Answers (2)

wirey00
wirey00

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();        
});​

http://jsfiddle.net/ycpFL/

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

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

Related Questions