0

.saf_search is a button, when it's clicked, the menu .lisearch fades in, when you click anywhere 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(); });
  });
ExodusNicholas
  • 1,634
  • 5
  • 15
  • 18

2 Answers2

1

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; });
});
PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
  • @peter why dont we use $(document).click(function(){ $(".lisearch").fadeOut(); }); – Shiva Srikanth Thummidi Feb 09 '10 at 20:08
  • it fades in and then back out again. this was the last question i posted about this and they gave the code to make it work, but i had to put together 2 different code pieces from 2 different answers. check this out if you would? http://stackoverflow.com/questions/2124684/jquery-how-click-anywhere-outside-of-the-div-the-div-fades-out – ExodusNicholas Feb 09 '10 at 20:44
  • You are correct the better way would be to use click. I have updated my answer to use that and to make sure that the click wasn't inside of '.lisearch' – PetersenDidIt Feb 09 '10 at 22:46
0

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
    });
});
Eric
  • 95,302
  • 53
  • 242
  • 374