Today I will present short code snippet in jQuery which will can be used to hide element on website by clicking outside of it. This snippet could be used ie. to present any information in popoup which should be visible while we do operate inside popup (ie. mark text to copy), but should be closed while we do a click outside or press enter.

Close on click outside element

$('body').click(function(e) {
  var container = $("#myElement");
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.hide();
  }
});

Close on Escape key press

$(document).keyup(function(e){
  if(e.keyCode === 27) {
    var container = $("#myElement");
    container.hide();
  }
});

Enjoy!

Hide element on click outside or Esc press
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

Social Widgets powered by AB-WebLog.com.