开发者

Jquery: fade menu out when clicking on anything EXCEPT the menu itself, short piece of code

.saf_search is a button, when it's clicked, the menu .lisearch fades in, when you click anywhe开发者_C百科re on the page EXCEPT for on the menu .lisearch, then it should fade out(that's how it's SUPPOSED to work) Does anyone know why this isn't working? It fades in, and the first time i click anywhere on the page it fades out, but the second time i try to fade in the menu, it will quickly fade out again without me clicking the document. i think this has to do with .one, but i had it working before my hard drive crashed, and now i can't figure out how to get it working again...

$('.saf_search').click(function() {
  $('.lisearch').fadeIn(200);
});

$(document).click(function(){
   jQuery(".lisearch").click(function(){ return false; });
jQuery(document).one("click", function() { jQuery(".lisearch").fadeOut(); });
  });


The reason is because you are using the "one" event binding function which binds to the event and only stays around for the first time its fired. Try this:

$(document).click(function(){
    $('.saf_search').click(function() {
        $('.lisearch').fadeIn(200);
    });
    $(document).click(function() { 
        //Make sure that the click isn't inside .lisearch
        if (!$(this).closest('.lisearch').length){
            $(".lisearch").fadeOut();
        }
    });
    $(".lisearch").click(function(){ return false; });
});


Any reason that you're wrapping the handlers inside an outer $(document).click(...)? Don't you want $(document).ready(...)?

$(document).ready(function(){
    $(document).click(function() {
        $(".lisearch").fadeOut();
    });
    $(".lisearch").click(function(){
        return false; //Prevent event propagation
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜