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?
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.
$(document). click(function (event) { $('#myDIV:visible'). hide(); });
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.
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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With