Modal windows Popaps on HTML CSS JavaScript Substituting Windows how to do it

This article explores how to create modal popups using HTML, CSS, and JavaScript, with an example to get you started.

Substituting Windows with Modal Windows Popups

The purpose of substituting windows with modal windows popups is to create a more interactive user experience. By making the user take action with a modal window, the user is more likely to pay attention to what is happening. This can be particularly useful when collecting important information or providing a warning.

To create a modal window popup, you will need to use HTML, CSS, and JavaScript. The HTML is used to create the structure of the window, the CSS is used to style the window, and the JavaScript is used to make the window popup when triggered. The following example shows how to create a basic modal window popup using the three languages.

HTML


<div id="modal">
  <div class="modal-content">
    <p>This is the modal window popup.</p>
    <button>Close</button>
  </div>
</div>

The HTML creates the modal window, the content inside the window, and the close button. The modal window has an ID of “modal”, which will be used by the CSS and JavaScript.

CSS


#modal {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
}

.modal-content {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  background: #fff;
}

The CSS is used to style the modal window. The window is positioned in the center of the page and has a background color of rgba(0, 0, 0, 0.6). The content inside the window is also positioned in the center and has a background color of #fff.

JavaScript


// Get the modal
const modal = document.getElementById('modal');

// Show the modal
function showModal() {
  modal.style.display = "block";
}

// Hide the modal
function hideModal() {
  modal.style.display = "none";
}

// Listen for close click
modal.addEventListener('click', (e) => {
  if (e.target.id === 'modal') {
    hideModal();
  }
});

The JavaScript is used to show and hide the modal window. The showModal() function shows the modal window and the hideModal() function hides the window. The addEventListener() method is used to listen for a click event on the modal window. If the target of the click event is the modal window, the hideModal() function is called to hide the window.

These three languages can be used together to create a modal window popup. The HTML is used to create the structure, the CSS is used to style the window, and the JavaScript is used to make the window popup when triggered. By using a modal window popup, you can create a more interactive user experience.

Answers (0)