Question

Please help me! I create a simple sliding block and I'm trying to make it close when you click anywhere on the page, except for sliding "black" content.

See JSFiddle: jsfiddle.net/2DaR6/233/

Javascript

$(".black ").hide();
$(".white").show();
$('.white').click(function(){
    $(".black ").slideToggle(150);
});

HTML

<div class="black">
    content
</div>

<a href="#" class="white">click me!</a><br />
Was it helpful?

Solution

Something like this perhaps http://jsfiddle.net/HE2Qg/

$(".black ").hide().click(function(){
    return false;
});
$(".white").show().click(function(){
    $(".black ").slideToggle(150);
    return false;
});
$(document).click(function(){
    $(".black ").slideUp(150);
});

OTHER TIPS

Try this.

http://jsfiddle.net/7QNnJ/1/

$(".black ").hide();
$(".white").show();
$('.white').click(function(e){
    $(".black ").slideToggle(150);
    e.stopPropagation();
});

$(document).on('click', function(e){
    if( !$('.black').is(":hover")){
        $('.black').slideUp();
    }
});

You'll want to change the click function:

$('.white').click(function(event) {
  $(".black ").slideToggle(150);
  event.stopPropagation();
});

And add these two functions:

$(".black").click(function(event) {
  event.stopPropagation();
});

$("html").click(function() {
  $(".black").slideToggle(150);
});

This will make it so that if you click anywhere on the page, the html's click handler will try to close the div. However, if you are clicking on the div or the "click me" link, event.stopPropagation() will prevent the event from reaching the html's click handler.

Here is a demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top