Creating a Modal Using JS

Photo by Greg Rakozy on Unsplash

Creating a Modal Using JS

Hello guys, Today I will be sharing with you how to create a simple modal using HTML, CSS, and JS. First off, I'll start by telling you what a modal is.

A modal is a pop-up that could appear on a website due to a call-to-action or just a random pop-up. For example, the image below contains a modal.

1 oTrpwGmHZ0gc_DQj0NOuow.jpeg

There are several cases where you might want to use a modal instead of just creating a blank HTML page to direct the user to. So let's get started. First, we'll add some markup

<html>
<body>
<button class='toggle'>Click me</button>
<div id='modal'>
 <p>This is a modal</p>
  <button class='close'>Close</button>
</div>
</body>
</html>

Alright, so what we're going to do is that we are going to set the display of the div with id="modal" to none using CSS. I'm not going to do much styling here because I want to keep this short and easy for you to understand. Now below is the code for the CSS. CSS

.toggle, .close{
  padding: 10px;
  background: wheat;
  border: none
}
.close {
  background: red
}
#modal {
  display: none;
}

Now you can add your own styling to this, like I said I'm keeping it very simple. After this, the modal will disappear because its display has been set to none.

Now, the last part is JavaScript. Here, we're going to dive into the DOM and target the two buttons we have there. That is the Click me and Close buttons. After that, we will add an event listener to listen for when the Click me button is clicked so that it can display the modal and do the same for the Close button so that it can also close the modal.

let btn = document.querySelector('.toggle');

let closeBtn = document.querySelector('.close')
let modal = document.querySelector('#modal');
btn.addEventListener('click',(e)=>{
  modal.style.display='block'
})
closeBtn.addEventListener('click',(e)=>{
modal.style.display = 'none'
})

And with this, it should function perfectly. This JS script is a bit long but it's for you to understand. You can just tap onto google and make this shorter. Thanks for reading.