Modal or popup windows are very useful elements of websites or webapps – you can display in it a notifications, additional or detailed information or it can be a “dialog window” in which user must take some decision, let’s say “Are you sure you want to delete the file?” So in general – there are hundreds of ways modal windows can be useful in web development.
Of course you can use dedicated JavaScript plugin/module to have modal windows available in your project, like e.g. bootstrap. But in many cases it is better to provide your own simple solution, not to mess your project with tens of external plugins or modules.
But creating modal window in vanilla JavaScript, HTML and CSS is very simple and you can do it with a small amount of code. So there is no need to take external JavaScript libraries for modal windows, you can just write it by yourself in a few easy steps.
Table of Contents
JavaScript modal window example
Let’s start ๐ In our example we will have 2 modal windows to open on one page. Why? Because it will show how to create a reusable JavaScript modal window component, not just modal window with hardcoded content inside itself.
The html modal window which we will create here will look like on image below:
You can open above JavaScript modal window example HERE.
Check whole code (vanilla JS, HTMl and CSS) of modal window described below on our Gitlab account HERE.
HTML of modal window
Let’s start creation of modal window from HTML code. We need 3 things here:
- Buttons to open modal window onclick – in our example. Of course you can trigger modal window with many different ways (check our example with detecting AdBlock users here which is one of many examples when modal window can be opened). In our case each button has additional HTML data-target attribute, like
data-target="modal-1"
which points to ID (check point 2) of modal window which will be opened. - HTML code of modal window with unique id, like
id="modal-1"
and classmodal-window
. This element contains whole content of the modal window. At the end of it is the closing button. - HTML element with fade background of modal window (semi-transparent black) with class
modal-fader
.
So long story short – we have 2 HTML modal windows with unique ID attributes and buttons with data attribute “data-target” which point to ID of wanted modal window. Last element is background of the modal window.
<button class="open-modal" data-target="modal-1">OPEN MODAL WINDOW 1</button> <button class="open-modal" data-target="modal-2">OPEN MODAL WINDOW 2</button> <div id="modal-1" class="modal-window"> <h2>Modal window 1</h2> <p>Proin rhoncus metus felis, ut tempor metus eleifend a. </p> <p>Nam porta, quam ut elementum sollicitudin, augue nibh ornare turpis.</p> <button class="modal-btn modal-hide">Close</button> </div> <div id="modal-2" class="modal-window"> <h2>Modal window 2</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <p>Nulla egestas sed mi sed fringilla. Maecenas a finibus neque.</p> <button class="modal-btn modal-hide">Close</button> </div> <div class="modal-fader"></div>
CSS code of modal window
CSS code for our popup window is quite simple. Let’s go through that step by step:
- We position in CSS the
.modal-fader
background element and set its background as semi-transparent black. By default, this element is hidden. - The
.modal-fader
element becomes visible (CSSvisibility: visible
) when “active” class is added to it:.modal-fader.active
. - Next element is
.modal-window
. It contains whole content of modal window. By default it is hidden, and, the same like modal-fader element, becomes visible with HTML class “active”:.modal-window.active
. - Next we have CSS styles for headers of modal window and the style of button inside modal window.
.modal-fader { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; width: 100%; z-index: 99998; background: rgba(0,0,0,0.8); } .modal-fader.active { display: block; } .modal-window { display: none; position: absolute; left: 50%; transform: translateX(-50%); z-index: 99999; background: #fff; padding: 20px; border-radius: 5px; font-family: sans-serif; top: 50px; } .modal-window.active { display: block; } .modal-window h1, .modal-window h2, .modal-window h3, .modal-window h4, .modal-window h5, .modal-window h6 { margin: 0; } .modal-btn { background: #36a5a5; border: none; color: #fff; padding: 10px 15px; box-shadow: none; border-radius: 3px; text-decoration: none; }
JavaScript code of modal window
Next, let’s go through JavaScript code of our popup window step by step. We have here only vanilla JavaScript code, without jQuery or other JavaScript library.
- On the very top of JavaScript code there is self-invoking function which contain the JavaScript code responsible for interactions with user interface – actions which triggers showing or hiding of modal window.
- Inside self-invoking function first we attach JavaScript onclick event to each button with class
open-modal
. Button click triggers first thehideAllModalWindows
function – which close all other opened modal windows (then we are sure that only 1 modal window is open at the same time) and nextยshowModalWindow
function is triggered which takethis
as parameter – in this case “this” is a button element itself. So this part of code in our example simply opens the modal window. - Next, inside self-invoking function we attach onclick event to all closing buttons. This buttons close modal window. By default, we always close all opened modal windows.
- Last part in self-invoking function is event fired onclick on modal window fade background
modal-fader
element – click here also close the modal window.
We have at the bottom of the script functions which show or hide modal window:
showModalWindow (buttonEl)
function takes here from buttonEl parameter the html element and takes itsdata-trigger
attribute, which is used in first function’s line to make the selector for wanted ID element of modal window. Modal window is opened by addingactive
class to its HTML element.hideAllModalWindows ()
function closes all modal windows. Normally, there should be only one modal window opened at the same time, but just in case, it hides all.
First it close.modal-fader
element by removingactive
class.
Next it close all modal windows in forEach loop also by removingactive
class.
The whole JavaScript code of modal window looks like below:
(function () { document.querySelectorAll(".open-modal").forEach(function (trigger) { trigger.addEventListener("click", function () { hideAllModalWindows(); showModalWindow(this); }); }); document.querySelectorAll(".modal-hide").forEach(function (closeBtn) { closeBtn.addEventListener("click", function () { hideAllModalWindows(); }); }); document.querySelector(".modal-fader").addEventListener("click", function () { hideAllModalWindows(); }); })(); function showModalWindow (buttonEl) { var modalTarget = "#" + buttonEl.getAttribute("data-target"); document.querySelector(".modal-fader").className += " active"; document.querySelector(modalTarget).className += " active"; } function hideAllModalWindows () { var modalFader = document.querySelector(".modal-fader"); var modalWindows = document.querySelectorAll(".modal-window"); if(modalFader.className.indexOf("active") !== -1) { modalFader.className = modalFader.className.replace("active", ""); } modalWindows.forEach(function (modalWindow) { if(modalWindow.className.indexOf("active") !== -1) { modalWindow.className = modalWindow.className.replace("active", ""); } }); }
You can open above JavaScript modal window example HERE.
Please, be aware that above code is working fully properly in all moderns browsers. This means it doesn’t support Internet Explorer browser. If you want to run it on IE11 or earlier, you must convert all HTML selected elements where forEach loop is triggered on real array by, as example:
Array.prototype.slice.call(document.querySelectorAll(".open-modal"), 0);
THE END ๐