How to open a popup modal on button click by HTML, CSS, and JS

If you want to open a popup modal on button click in your web page, follow these steps: How to open a popup modal on button click by HTML, CSS, and JS

1. First of all add the following CSS in your code file Head tag:

<style>
.modal {
  display: none;
  position: fixed; 
  z-index: 1;
  padding-top: 100px; 
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
</style>


2. Then, add the following HTML code of button and Modal inside the body tag in your code file:

<button id="myBtn">Open Modal</button>


<div id="myModal" class="modal">


  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>


3. Then, add the following JS code of inside the body tag in your code file:

<script>
var mymodal = document.getElementById("myModal");

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  mymodal.style.display = "block";
}
span.onclick = function() {
  mymodal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == mymodal) {
    mymodal.style.display = "none";
  }
}
</script>
Now you can see your popup modal like this:

How to open a popup modal on button click by HTML CSS and JSexpoundsofttechsolution