Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding a div with esc key, and off click? In Jquery [closed]

if I have a div I've shown thanks to a click event - what are some easy was to make it close if someone clicks anywhere outside the div, or hits the esc key?

like image 430
Elliot Avatar asked Feb 17 '12 18:02

Elliot


People also ask

How do you close a div when clicking outside?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.

How do I hide a div by clicking anywhere on the page?

$(document). click(function (event) { $('#myDIV:visible'). hide(); });

How do I stop pop ups on escape?

We can use Esc key to close dialogue boxes or any custom popup modals. Here we will discuss even handling on ESC key press in which we can fire any event we want.


2 Answers

Here you go...

$( document ).on( 'click', function ( e ) {
    if ( $( e.target ).closest( elem ).length === 0 ) {
        $( elem ).hide();
    }
});

$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) { // ESC
        $( elem ).hide();
    }
});

Live demo: http://jsfiddle.net/S5ftb/

like image 86
Šime Vidas Avatar answered Sep 20 '22 19:09

Šime Vidas


For those of you who prefer vanilla:

<div id="div">Click me dude</div>

<script>
    d = document.getElementById("div");
    d.addEventListener("click",     function(e){e.stopPropagation()},true);
    addEventListener("click",       function() {d.style.display="none"},false);
    addEventListener("keypress",    function(e){e.keyCode==27 &&(d.style.display="none")},false);
</script>
like image 26
Jeffrey Sweeney Avatar answered Sep 22 '22 19:09

Jeffrey Sweeney