0

I have a simple requirement that I am struggling with.

Using jquery, I would like to click a link to show a div then be able to click on anywhere BUT the content that is now shown to hide it again.

I have accomplished the first part, I can fadeIn/Out the div by clicking the link. But I am not sure how I could add that instead of only clicking on the link to fade out, it would be that you could click anywhere but the blue content area to fade out.

http://jsfiddle.net/4hchhhcd/2/

So you fade in by clicking the link but fade out by clicking anything but the content that was shown.

$("#clickme").click(function() {
  $("#extra").fadeToggle();
});

I've thought of targeting html or document to close but that doesn't work as #clickme is within this.

Craig van Tonder
  • 7,497
  • 18
  • 64
  • 109

2 Answers2

2

You can use following logic which handles any descendants click inside targeted element:

$("#clickme").click(function(e) {
    e.stopPropagation();
    $("#extra").fadeToggle();
});

$(document).click(function(e) {
    if (!$(e.target).closest('#extra').length) {
        $('#extra').fadeOut();
    }
});

-DEMO-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1
$("#clickme").click(function () {
    $("#extra").fadeIn();
});
$(document).click(function (event) {
    if (event.target.id !== 'clickme') {
        $("#extra").fadeOut();
    }
})

You need to leave the case when the link is clicked. Fiddle edited.

bluefog
  • 1,894
  • 24
  • 28