Skip to content

Instantly share code, notes, and snippets.

@jenhuls
Last active April 15, 2022 12:28
Show Gist options
  • Save jenhuls/a112d755e33cd312dcbd0d469d8a4e09 to your computer and use it in GitHub Desktop.
Save jenhuls/a112d755e33cd312dcbd0d469d8a4e09 to your computer and use it in GitHub Desktop.
[Simple Modal] #js
/* jshint esversion: 6 */
// @link: https://screenspan.net/blog/multiple-modals/
// Get each modal and close button
const triggers = document.getElementsByClassName("trigger");
const triggerArray = Array.from(triggers).entries();
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) {
const toggleModal => () {
modals[index].classList.toggle("show-modal");
};
trigger.addEventListener("click", toggleModal);
closeButtons[index].addEventListener("click", toggleModal);
}
<!-- Elements used for triggering modals to open -->
<button class="trigger">Modal 0</button>
<!-- Elements used as modals -->
<div class="modal" aria-role="dialog">
<!-- Content -->
<div class="modal-content"><span class="btn-close">×</span>
<p>Modal Header 01</p>
<p>Modal Content</p>
</div>
</div>
// Edit to match design
.modal {
align-items: center;
background-color: rgba(black, 0.5);
display: flex;
height: 100%;
justify-content: center;
left: 0;
opacity: 0;
position: fixed;
top: 0;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
visibility: hidden;
width: 100%;
z-index: 15;
&-content {
align-self: center;
background-color: transparent;
border-radius: 0.5rem;
padding: 0;
width: 50vw;
}
&.show-modal {
opacity: 1;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
visibility: visible;
}
.btn-close {
background-color: white;
border-radius: 50px;
color: black;
cursor: pointer;
font-size: 30px;
float: right;
line-height: 2.75rem;
text-align: center;
transition: color 500ms ease-out;
width: 2.75rem;
&:hover {
color: #8cbf40;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment