📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials jQuery in Practice Modals with jQuery

Modals with jQuery

5 min read
Build a modal by showing an overlay and dialog on button click. Close on Escape key and overlay click. Always move focus into the modal on open and restore it to the trigger button on close for accessibility.

Building a Modal

// Open
$('#openBtn').on('click', function() {
  $('#modal').fadeIn(200);
});

// Close on overlay click
$('#modal').on('click', function(e) {
  if ($(e.target).is('#modal')) {
    $('#modal').fadeOut(200);
  }
});

// Close on Escape key
$(document).on('keydown', function(e) {
  if (e.key === 'Escape') $('#modal').fadeOut();
});