Hide container the right way

After displaying a container on click, hide it by: clicking outside, clicking on the Close button or pressing ESC key.

by rzea

HTML

<a href="#" class="trigger">Open</a>
<div class="flyout">Lorem ipsum <a href="#" class="btn-close">[×]</a></div>

CSS

.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 {}

JavaScript

//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");
  }
});