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
Podobne wpisy:
- sgCounter - jQuery plugin which supports length control in form fields
- Zbiór ciekawych zastosowań Bootstrap i jQuery
- jQuery - przygotowanie i wysłanie danych JSON z wykorzystaniem AJAX
- Informacja o cookies - gotowe rozwiązanie
- jQuery validation - własne walidatory
- Elementy graficzne w aplikacji - ikony