Create a Modal pop up box using CSS and Javascript

Modal box in a Website

The Modal is a dialog box/pop up window that shows in the current page of the website. It creates a mode that disables the main window but keeps it visible with the modal window as a child window in front of it. Either user can make the action on the modal box or they can ignore this box by clicking outside of the modal box.

Use of Modal box

  • It grabs the user’s attention and interrupts their task for important information
  • It is used to get the user inputs for signup/login.

Examples for Modal box

  • To get the email address from the user for the subscription on the website
  • To show the Offers or other important Announcements
  • To display the warning or error messages on the user actions

Creation of simple modal box using Javascript and CSS

Lets create the modal box for email subscription using Javascript and CSS. In this example, we are going to create the three files such as index.html, style.css and main.js under the same folder

Index.html

The button “subscribe to our newsletter” is created in the body. If user click’s this button, we need to show the modal box to get the user email address. The div element is “simpleModal” is created with the class name as “modal“.

Inside the div element, we have created the form with text box and button for email subscription.

style.css

The CSS properties are created for the html elements and modal box. The modal class properties are added to design the modal window. Similarly the style properties are added for the modal contents. Here modal contents are close button(X) , email address text box and Join now button.

Also animations are added for the modal contents using keyframe properties.

main.js

User might perform the following actions in our web page.

  • Click the subscribe button to get the email subscription box (modal box)
  • Click the close button(x) on the modal box
  • Click the outside of modal box.

For those actions, we need to define the respective functions in Javascript. To get the value from the HTML page, we have defined the variables using document.getElementById and document.getElementsByClassName.

Using that variable, we are calling the respective functions using addEventListener method.