jQuery Modal Popup Example
A modal is a box which opens over the page. This code opens it with a button and closes it with the close button, a click on the dark background, or the Escape key.
HTML
<button id="open-modal">Open popup</button>
<div id="overlay" class="overlay" style="display:none">
<div class="modal">
<button class="close" aria-label="Close">×</button>
<h3>Hello!</h3>
<p>This is a popup made with jQuery.</p>
</div>
</div>
CSS
.overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,.6);
display: flex; align-items: center; justify-content: center; }
.modal { background: #fff; padding: 20px; border-radius: 6px; min-width: 280px; position: relative; }
.close { position: absolute; top: 6px; right: 10px; border: 0; background: none; font-size: 22px; cursor: pointer; }
jQuery code
var $overlay = $('#overlay');
function openModal() { $overlay.fadeIn(150).css('display', 'flex'); }
function closeModal() { $overlay.fadeOut(150); }
$('#open-modal').on('click', openModal);
$('.close').on('click', closeModal);
// click on the dark background, but not inside the box
$overlay.on('click', function (e) {
if (e.target === this) closeModal();
});
// Escape key
$(document).on('keyup', function (e) {
if (e.key === 'Escape') closeModal();
});
// test
$('#open-modal').click();
console.log('after open: ' + $overlay.css('display'));
$(document).trigger($.Event('keyup', { key: 'Escape' }));
console.log('after Escape: ' + $overlay.css('display'));
Console output
after open: flex
after Escape: none
How it works
e.target === thischecks that the click was on the overlay itself, and not on the box inside it.- The keyup event on the document handles the Escape key.
- The overlay uses
display: flexto center the box, so we set the display to flex afterfadeIn().
Note:
For a good popup also move the focus into it, keep the focus inside while it is open, and give it role="dialog" for screen readers. See jQuery Events.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |