views:

114

answers:

3
+2  Q: 

Hide list on blur

Hi, I have a list showing up when i click on button, the problem is that i want to hide the list whenever it loses focus i.e. user clicks anywhere on a page, but not on that list. How can i do this? Also, you can see how it should look at last.fm, where's list of profile settings (li.profileItem). (ul.del li ul by default is display:none) Basic list structure:

<ul class='del'>
    <li>
        <button class='deletePage'></button>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </li>
</ul>

My function for displaying this list:

$(".deletePage").click(function(){
    if( $(this).siblings(0).css("display") == "block" ){
        $(this).siblings(0).hide();
    } else {
        $(this).siblings(0).show();
    }
});
+1  A: 

See How to detect a click outside an element?

You can bind a click handler to the document to hide the list, then attach a separate handler to the button which calls event.stopPropagation.

$(document).click(function() {
 $('.list-to-hide').hide();
});

$('.show-list-button').click(function(event) {
 event.stopPropagation();
});

Alternatively, you could use the jQuery outside events plugin:

$('.show-list-button').bind('clickoutside', function() {
 $('.list-to-hide').hide(); 
});
Mathias Bynens
event.stopPropagation() worked beatifully, thanks!
bah
A: 

Check out Ben Alman's "Outside Events" plugin which adds the ability to bind('clickoutside') to handle things like this.

PetersenDidIt
+1  A: 

You can use the document click event. If the user clicks inside the div the event propagation stops there (e.stopPropagation) else it will be handled by the document click event which checks if the menu is open and if it is closes it.

$(document).click(function() { 
  // check if the menu is open, if so close it
});

$("#windowdiv").click(function(e){
  e.stopPropagation();
  // do stuff
});
Fabian