Pergunta

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 />
Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top