Plain Modal Window With JavaScript And CSS

Category: Javascript , Modal & Popup | September 16, 2017
Author: gwolf2
Views Total: 1,120 views
Official Page: Go to website
Last Update: September 16, 2017
License: MIT

Preview:

Plain Modal Window With JavaScript And CSS

Description:

Makes use of plain JavaScript and CSS to create responsive modal popups in the screen.

How to use it:

Create the modal content as follow:

<div id="simpleModal" class="modal">
  <div class="modal-content">
    <span class="closeBtn">&times;</span>
    <p>Hello... I am a modal</p>
  </div>
</div>

Create a button to toggle the modal.

<button id="modalBtn" class="button">Launch</button>

Style the modal window in the CSS.

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #f4f4f4;
  margin: 20% auto;
  padding: 20px;
  width: 70%;
  box-shadow: 0 5px 8px 0px rgba(0, 0, 0, 0.2), 0 7px 20px 0px rgba(0, 0, 0, 0.17);
  animation-name: modalopen;
  animation-duration: 1s;
}

.closeBtn {
  color: #ccc;
  float: right;
  font-size: 30px;
}

.closeBtn:hover, .closeBtn:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

@keyframes 
modalopen {  from {
opacity: 0
}

to { opacity: 1 }
}

The main JavaScript.

// Get modal element
var modal = document.getElementById('simpleModal');

// Get open modal button
var modalBtn = document.getElementById('modalBtn');

//Get close button
var closeBtn = document.getElementsByClassName('closeBtn')[0];

// Listen for open click
modalBtn.addEventListener('click', openModal);

// Listen for close click
closeBtn.addEventListener('click', closeModal);

// Listen for outside click
window.addEventListener('click', clickOutside)

// Function to open modal
function openModal() {
  modal.style.display = 'block';
}

// Function to close modal
function closeModal() {
  modal.style.display = 'none';
}

// Function to close modal if outside click
function clickOutside(e) {
  if (e.target == modal) {
    modal.style.display = 'none';
  }  
}

You Might Be Interested In:


Leave a Reply