top of page

Modal

  • Writer: kwangjin baek
    kwangjin baek
  • Dec 11, 2022
  • 2 min read

A modal in web programming refers to a popup or a dialog box that appears on top of the page to interact with users. Modal is a great way to get users' attention. Let's see how to implement is with HTML, CSS and JavaScript

How to do it


First, we need a modal in the HTML. In this example, I kept the code as simple as possible so that we can focus on the topic.


HTML

In the HTML, put modal element

<body>
  <button id="auth">auth</button>

  <!-- modal -->
  <div class="modal">
    <form>
      <i id="close">❌</i>
    </form>
  </div>
  <!-- modal -->
</body>

CSS

To make the modal element to be out of the flow we can either use position: absolute; or position: fixed; I prefer to use position: fixed; because this always covers the whole screen regardless of the content size. Hide the element with the property of your choice, I used display:none; here for the simplicity.

.modal {
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;  
  background-color: rgba(0, 0, 0, .3);
  display: none;
  align-items: center;
  justify-content: center;
}

form {
  height: 300px;
  width: 300px;
  background-color: aliceblue;
  position: relative;
}

i {
  position: absolute;
  top: 5px;
  right: 10px;
  cursor: pointer;
}

JS

For JavaScript, implement click events as follow. Then it is done!

const auth = document.getElementById('auth')
const modal = document.querySelector('.modal')
const close = document.getElementById('close')

// opens modal
auth.addEventListener('click', () => {
  modal.style.display = 'flex'
})

// closes modal when X icon is clicked
close.addEventListener('click', () => {
  modal.style.display = 'none'
})

// closes modal when anywhere outside the modal form is clicked
modal.addEventListener('click', (e) => {
  modal.style.display = 'none'
})

Conclusion

There are many ways to implement the same feature and I showed you one of the ways that I use often. I prefer using a modal instead of creating a separate page whenever possible for the simplity and clarity it provides.


Reference





 
 
 

Comments


  • github-sign
  • LinkedIn

©2022 by Dev Log. Proudly created with Wix.com

bottom of page