Handling Multiple Modals on One Page with Vanilla JS

Here is a little JS snippet for opening and closing multiple modals on a page

Sometimes I have little prototypes or one-pagers that have multiple modal overlays.

Giving each modal an unique name bloats up the code and gets out of hand – especially if you’re using vanilla JavaScript:

<!-- Elements used for triggering modals to open -->
<button class="modal-trigger" id="modal-1-trigger">
<button class="modal-trigger" id="modal-2-trigger">
<!-- Elements used as modals -->
<div id="modal-1" class="modal">

<div id="modal-2" class="modal">

let modal1 = document.getElementById('modal-1');
let modal2 = document.getElementById('modal-2');
let modal1Trigger = document.getElementById('modal-1-trigger');
let modal2Trigger = document.getElementById('modal-2-trigger');

function toggleModal() {


Use For…Of-Loops for Modals

So instead of explicitly naming and calling each modal, modal trigger and close button, I use arrays and for...of-loops like so:

In the HTML, give each modal trigger the same class name. Then in the JS, get those elements by the class name and store them in an array:

const triggers = document.getElementsByClassName("trigger");
const triggerArray = Array.from(triggers).entries();

Get each modal and close button:

const modals = document.getElementsByClassName("modal");
const closeButtons = document.getElementsByClassName("btn-close");

Then use for...of-loop with the index of each item in triggerArray for listening to a click event which toggles each modal to open and close:

for (let [index, trigger] of triggerArray) {
let triggerIndex = index;
function toggleModal() {
trigger.addEventListener("click", toggleModal);
closeButtons[triggerIndex].addEventListener("click", toggleModal);

The result:

See the Pen Loop to get modals by screenspan (@screenspan) on CodePen.

Published: Feb 16, 2018

More from my blog