Introduction
Modals are one of the more common components you'll see on the internet. They're used for things likes image lightboxes, website search forms, mobile menus, and more.
There's surprisingly a lot that can go into a simple modal so building a reusable component is a great way of taking care of some of the basic functionality.
Functionality
We can add some of the basic functionality like trapping focus inside the modal and allowing users to close the modal by pressing escape inside the <script>
tags.
scripts
The HTML
Next, we can add the modal html, including an overlay and some nice Svelte transitions.
the html
Basic Styling
Now we can add some very basic styling. The most important piece we'll add is overflow: hidden;
to the html and body element when the modal is opened. We added an optional class of window-scroll
when the modal is open with the following, class:window-noscroll={isOpen}
. Anytime a modal has the window-noscroll
class we’ll make sure the html and body elements overflow is hidden.
modal styles
Using the Component
Now that we have our modal component we can use it anytime we want to add a modal to our website.
svelte
Full Modal Component
Modal.svelte
Was this post helpful?