Skip to content

Instantly share code, notes, and snippets.

@ricardozea
Last active March 21, 2019 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardozea/2d2fea9c9138b8ead080cb3951796e27 to your computer and use it in GitHub Desktop.
Save ricardozea/2d2fea9c9138b8ead080cb3951796e27 to your computer and use it in GitHub Desktop.
After displaying a container on click, hide it by: clicking outside, clicking on the Close button or pressing ESC key. Demo here: http://jsfiddle.net/rzea/3p9n2vsb/2/
.flyout {
display: none;
width: 200px;
height: 200px;
margin: 1em;
padding: 20px;
position: relative;
background: #ccc;
}
.btn-close {
position: absolute;
top: 5px;
right: 5px;
}
/* Styles not needed for demo */
html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }
body {
margin: 20px;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
a {}
<a href="#" class="trigger">Open</a>
<div class="flyout">Lorem ipsum <a href="#" class="btn-close">[×]</a></div>
//Variables
var trigger = $(".trigger");
var flyout = $(".flyout");
var close = $(".btn-close");
//Fade in/out the flyout when clicking on the trigger
$(trigger).on("click", function(e) {
$(flyout).fadeToggle("fast");
e.stopPropagation();
});
//Fade out the flyout when clicking on the Close button
$(close).on("click", function(e){
$(flyout).fadeToggle("fast");
e.stopPropagation();
});
//Fade out the flyout when clicking anywhere on the page
$(document).on("click", function(e) {
if ($(e.target).closest(flyout).length === 0) {
$(flyout).fadeOut("fast");
}
});
//Fade out the flyout when pressing the ESC key
$(document).on("keydown", function(e) {
if (e.keyCode === 27) {
$(flyout).fadeOut("fast");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment