DEV Community

Cover image for Modal Made Easy
Thomas Fitzgerald
Thomas Fitzgerald

Posted on

Modal Made Easy

I'm back again and sharing showing another feature I learned while working on my profile site; Modals! This is what the finished product will look like:

Let's get started with the HTML structure.

Alt Text

Now we have a simple button that is used to activate the modal. We also have the modal container which becomes the actual modal and last, but not least, we have the content that goes inside the modal.

Now it's given CSS to make it look good.

Alt Text

You can add as much style as you'd like and I encourage you to do so. I've left it clean and simple for the sake of this tutorial, but please showcase your skills and reply with a link.

So, what have we actually done?

The .modal class creates the overlay looking background color when it's activated. It needs to be the full width and height of the screen. Next, we are hiding it so it doesn't appear until we want it to.

For .the-content class we simply want to give the actual modal some visual cues and set it to the middle of the screen.

.close-button and .close-button:hover gives the user a clear way to close the modal when actions are complete.

Lastly we need to add the .active class. This functionality will be handled by a bit of JavaScript which will be added next.

Alt Text

This bit of JavaScript is what makes the modal actually work.

First we grab the modal, the button and close button and create a custom function that will toggle the .active class.
This allows us to activate the modal when the user clicks the button and hides the modal when the close button is clicked. We can also hide the modal by clicking on the dark background.

That's it! Now you have a clean and simple modal with a smooth animation while opening and closing. Please comment with a link of your finished product. Thank you for bearing with me as I continue to teach what I've learned so far on my coding journey!

Discussion (1)

Collapse
nbhankes profile image
Nathan B Hankes

Great tutorial. Thanks for sharing your work!