-1

I have a div, #blue. When you click on #blue, another div, #green is shown. How can I make it so that if you click any where other than #blue, #green is hidden.

JSFIDDLE: http://jsfiddle.net/8Q2nN/

My JQuery:

$(document).ready(function() {
    $("#blue").click(function() {
        $("#green").show();
    });
});
user2320500
  • 169
  • 3
  • 10

3 Answers3

3

You can bind click event on body and hide the div with id green if the event source is not element with id blue. You can get the source of click event through event object using event.target and use it id to determine if source is element with id blue

Live Demo

$('body').click(function(event){
    if(event.target.id != 'blue')
       $("#green").hide();
});
Adil
  • 146,340
  • 25
  • 209
  • 204
2

http://jsfiddle.net/8Q2nN/1/

Easy, hide it when you click outside of blue. Uses .stopPropagation() to stop clicks on blue from bubbling up to the document.

$("#blue").click(function(e) {
    e.stopPropagation();
    $("#green").show();
});
$(document).click(function() {
   $("#green").hide(); 
});
megawac
  • 10,953
  • 5
  • 40
  • 61
0

This can be done by simply adding:

$('body').click(function(event){
      if(event.target.id != 'blue')
         $("#green").hide();
});

After the code:

$(document).ready(function() {
    $("#blue").click(function() {
        $("#green").show();
    });
});

This code makes it so that whenever you click on an area that is not the blue div, it will hide the green. You can also input parameters within the hide() function to change how it hides, such as "slow" or "fast"

Live demo with the slow parameter in the function.

You can fiddle around with the parameters to make it how you want it to be when not clicking on it. If you would like it to simply disappear, just leave the .hide() function blank in the parentheses ().

Domecraft
  • 1,645
  • 15
  • 26