How To Make A Modal With Javascript

Gina Lee
Gina Lee
Sep 4, 2018 · 3 min read
JavaScript modal feature

I really wanted to make this website easy flowing by having all the content on the same site, without the user being navigated to a whole new page. My solution was to have a modal appear right on top of the main webpage. For this example, I have put modals for the About, Contact, and Dine In buttons.

window.onload = function() {

// your code here

};

Function runs when the entire webpage loads.


Lines 4–6 assigns variable names to each of my modal contents. The document.getElementById(“id-name”) function will find the element with an id of whatever is in the parameter.

Lines 8–10 assigns variable names to the buttons that will make the modals appear.

Lines 12–13 assigns variable names to the close buttons. (Note: Because this is a document.getElementByClassName(“class-name”) function with multiple elements that have that class name, they each have an index for the instances when they were declared.)


element.onclick = function() {

// your code here

};

Function runs when user clicks on the element.

element.style.display = “ style ”;

This function sets the element to the style declared. In this example, the modal contents will start with a display styling of “none” (won’t be visible to the user), then will change to “block” after the user clicks on the button.


The final function in the script.js file allows the user to close the modal by clicking anywhere on the webpage.


The modal content for the “about” will be placed right under the background image div.

The modal content for the “contact” will be placed right under the about modal.

contact modal
contact modal continued

And the dine in modal will be placed right underneath that.

dine in modal

Finally, don’t forget to add the id name for the buttons.

id names for the buttons are highlighted

And the animation code.

animation code added in CSS file

Webkit is the browser rendering engine for Safari and Chrome.

@keyframes rule specifies the animation code. These animations will be used in our element stylings.


Extra styling for the modals —


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade