Jquery toggle the visibility of a UI element, but make it invisible if no part of that div is clicked

Go To StackoverFlow.com

1

This is similar to the facebook and google notification buttons, where you click on them and pops up a window, and closes if you click that button again or if you click on any part that isn't part of the notification div.

My problem is I can't find an event for unclicking an object or clicking out of it.

This is what I have now, where you can only close what pops up if you re-click the button.

notifycounter.click(function() {
    return imagepanel.toggle();
});

This is what I've tried, but neither events fire:

notifycounter.focusin(function() {
  return imagepanel.toggle();
});
notifycounter.focusout(function() {
  return imagepanel.hide();
});

notify counter is an h3

image panel is an img

2012-04-03 19:39
by prashn64
Why return... - elclanrs 2012-04-03 19:42


2

Try this.

notifycounter.click(function(e) {
    imagepanel.toggle();
    e.stopPropagation();//this will stop the event bubbling
});

$(document).click(function(){
   if(imagepanel.is(':visible')){
      imagepanel.hide(); 
   }
});

You can optimize it little more like this.

notifycounter.click(function(e) {
    imagepanel.toggle();
    e.stopPropagation();//this will stop the event bubbling

    if(imagepanel.is(':visible')){
        $(document).one('click.imagepanel', function(){
             imagepanel.hide(); 
        });
    }
    else{
        $(document).unbind('click.imagepanel');
    }
});
2012-04-03 19:43
by ShankarSangoli
Wrap the .hide() inside a if( imagepanel.is(':visible') ){ could help - Roko C. Buljan 2012-04-03 19:49
@RokoC.Buljan - Yes, it makes sense - ShankarSangoli 2012-04-03 19:50
Nice one +1 from m - Roko C. Buljan 2012-04-03 19:51
Thanks a lot for the concise code - prashn64 2012-04-03 20:01


1

You can bind to the document element and check if the target of the event is the correct element:

$(document).on('click', function (event) {
    if (event.target == 'my-element-id') {
        //the element was clicked-on
    } else {
        //something other than the element was clicked-on
        $('#my-element-id').hide();
    }
});

You can also use event.stopPropagation() to stop the event from propagating up to the document element: http://api.jquery.com/event.stopPropagation/

$('#my-element-id').on('click', function (event) {
    event.stopPropagation();
});
$(document).on('click', function () {
    $('#my-element-id').hide();
});

Only clicks on elements other than #my-element-id will trigger the documents click event handler.

Note that .on() is new as of jQuery 1.7 and in this case can be replaced with .bind() if you are using an older version: http://api.jquery.com/on

2012-04-03 19:41
by Jasper
Thanks for the quick response and the nice explanation - prashn64 2012-04-03 20:02
Ads