RU EN

Vanilla JavaScript modal with multiple open/close handlers

Автор:
Источник:
Просмотров:
1367
Vanilla JavaScript modal with multiple open/close handlers favorites 0

In this post I want to show how we can easily create a modal with vanilla JavaScript. It can have multiple open/close handlers thanks to querySelectorAll.

First of all lets create the HTML structure for our modal.

<div class="modal">
  <span class="modal-backdrop"></span>
  <div class="modal-content">
    <div class="modal-header">
      <h2 class="modal-title">Modal Title</h2><button class="close-modal">&times</button>
    </div>
    <div class="modal-body">
      <h3>Modal body</h3>
      <p>Modal body text</p>
    </div>
    <div class="modal-footer">
      <button class="close-modal">Ok</button>
      <button class="close-modal">Cancel</button>
    </div>
  </div>
</div>

Now lets add some style.

.modal {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 2rem;
  position: fixed;
  width: 100%;
  top: 0;
  visibility: hidden;
  opacity: 0;
  transition: all 0.3s ease;
}
.modal .modal-backdrop {
  background: rgba(0, 0, 0, 0.7);
  height: 100%;
  width: 100%;
  position: fixed;
}
.modal .modal-content {
  background: #fff;
  border-radius: 5px;
  max-width: 600px;
  position: fixed;
  top: -100%;
  transition: all 0.6s ease;
  z-index: 1000;
}
.modal .modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
  padding: 1.5rem;
}
.modal .modal-header .close-modal {
  font-size: 2rem;
  padding: 0;
  margin: 0;
  height: 30px;
  width: 30px;
  text-align: center;
}
.modal .modal-header .close-modal:hover {
  color: #000;
}
.modal .modal-body {
  padding: 1.5rem;
}
.modal .modal-footer {
  border-top: 1px solid #ccc;
  padding: 1rem;
  text-align: right;
}

Notice that 3 attributes on .modal class.

.modal {
  ...
  top: 0;
  visibility: hidden;
  opacity: 0;
}

It will keep the modal hidden by default, later we will use JavaScript to add a .visible class to make our modal appear on the screen.

Time to JavaScript

Finally lets write some JavaScript code to give interaction to the modal.

We begin finding what we need to interact in the DOM.

const modal = document.querySelector('.modal'),
      openHandlers = document.querySelectorAll('.open-modal'),
      closeHandlers = document.querySelectorAll('.close-modal');

Now we loop through our open and close handlers to add it a click eventListener.

openHandlers.forEach(openHandler => {
  openHandler.addEventListener('click', openModal)
});

closeHandlers.forEach(closeHandler => {
  closeHandler.addEventListener('click', closeModal)
});

We added a call to an open and and close functions when the click event gets fired. Lets create these two.

function openModal() {
  modal.classList.add('visible');
}

function closeModal() {
  modal.classList.remove('visible');
}

When our openModal function gets fired, we simply add a class .visible to the main .modal class.
So we can toggle its visibility with CSS.

.modal.visible {
  opacity: 1;
  visibility: visible;
}
.modal.visible .modal-content {
  top: 25%;
}

Notice the:

top: 25%

It's just to add some cool animation in out.

Thats all we need and our modal is ready.
Vanilla JavaScript is pretty easy nowadays, in the past it would be a pain in the ass to make such a simple thing.

Check the demo on codepen to see it in action.

Файлы

Похожее
Mar 11, 2024
Author: Zafer Ayan Zafer Ayan
The Fetch vs Axios debate has been going on for years and recently it has come up again. I will talk about the disadvantages of using the Fetch API directly instead of using a network library like Axios. First of...
30 октября 2024 г.
Автор: Дмитрий Брайт
JS-библиотеку htmx воспринимают как средство, которое спасает интернет от одностраничных приложений. Всё дело в том, что React поглотил разработчиков своей сложностью (так говорят), а htmx предлагает столь желанное спасение. Создатель htmx, Карсон Гросс, иронично объясняет эту динамику библиотеки так: Нет,...
Dec 16, 2024
Author: Alex Booker
Imagine having to restart WhatsApp whenever you anticipate a new message, or needing to reload the page every time you expect an update on the big game. That would be a terrible user experience! Today, users expect the UI to...
Mar 23, 2022
Why do we need lifecycle hooks? Modern front-end frameworks move the application from state to state. Data fuels these updates. These technologies interact with the data which in turn transitions the state. With every state change, there are many specific...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Задача по языку C#: Игра «Крестики Нолики» в консоли
Принципы построения REST JSON API
Вопросы с собеседований, которые означают не то, что вы думаете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Три дороги для программиста: эксперт, руководитель, основатель
ИИ не оправдал надежд? Бизнес массово отказывается от новых технологий
Как мы столкнулись с версионированием и осознали, что вариант «просто проставить цифры» не работает
Три способа отладки T-SQL кода
Переход от монолита к микросервисам: история и практика
Boosty
Donate to support the project
GitHub account
GitHub profile