Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  167] [ 5]  / answers: 1 / hits: 40331  / 13 Years ago, fri, february 17, 2012, 12:00:00

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?


More From » jquery

 Answers
21

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/


[#87398] Thursday, February 16, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reesel

Total Points: 345
Total Questions: 124
Total Answers: 119

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
;