4

I have a <div> that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.

I tried using
e.stopPropagation();
and
e.preventDefault();

adding it to the click event of that certain DIV but that didn't work.

Thanks!

Timo Tijhof
  • 9,867
  • 6
  • 33
  • 47
Ovi
  • 2,357
  • 9
  • 49
  • 72

2 Answers2

4

Toggle a flag on popup hover:

JSBin demo

var $pop   = $('#popup'),
    notHov = 1; // Hover flag

$pop.hover(function(){ notHov^=1; }); // Toggle flag on hover

$(document).on('mouseup keyup', function( e ){
  if(notHov||e.which==27) $pop.fadeOut();
});

Note:
if somewhere on the page you have an element the prevents the mouseup event to bubble up the DOM tree reaching document (in order to be registered), you might want to create a full-screen (like an page-overlay) popup wrapper to register the click events, changing in the code above just the selector: instead of $(document) would be $('#popupWrapper')

Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292
  • thank you. but it didnt work for me, maybe cuz i am using iframe? and the div i want to hide i add it on a event click? does that make sense? – Ovi May 29 '11 at 06:44
  • Well, have you tried to just change to: ).live('click',function(ev) – Roko C. Buljan May 29 '11 at 10:19
  • Can you please write for me the full way of using ).live()? my problem is also cuz that div that i need to hide only appears after a click on something else, so its confusing.. any ideas? – Ovi May 30 '11 at 05:55
  • Thank you, when i do the above code you wrote it now doesnt allow me to click on the select box that opens the div that after it is open i need to close it if user click any where out side that div. (all in iframe) – Ovi May 30 '11 at 19:15
  • @Ovi JSFiddle was busy... so I made a JSBIN: look above! – Roko C. Buljan May 30 '11 at 19:45
  • @roXon, I used your code and it was great, but now in the div that needs to be closed i have a few more elements, that also when you click on them it shouldn't close, but it crazy to do allot of 'if' , is there a way using 'ev.target.id;' or something to get the parent element and then to see if that is the id i have? thank you – Ovi Jun 14 '11 at 05:20
  • Between your [other](http://stackoverflow.com/a/13514997) [answers](http://stackoverflow.com/a/23284144) about this topic this is the easier to implement – Cliff Burton Sep 14 '16 at 10:48
2

Probably the easiest way to do this will be to monitor clicks on the entire document, and ignore it if it's not that element. If it is, then hide it.

(function(div) {
    $(document).click(function(e) {
        if (e.srcElement !== div) $(div).hide();
    });
})($('div')[0]);

Edit: Derp, misunderstood, click inside should stay, otherwise hide... invert the equality check.

http://jsfiddle.net/robert/QcPx4/

Robert
  • 20,680
  • 9
  • 53
  • 64