Exercise: Creating a Modal Window with Vanilla JavaScript

Exercise: Creating a Modal Window with Vanilla JavaScript

https://basescripts.com/exercise-creating-a-modal-window-with-vanilla-javascript

Modals are a common feature in web development, used to display content in an overlay that pops up on top of the main page. They are typically used for dialogs, alerts, forms, or any content that requires the user's immediate attention. In this blog post, we will walk through how to create a simple modal window using vanilla JavaScript, HTML, and CSS.

What is a Modal Window?

A modal window is a graphical control element that temporarily blocks interaction with the main page until the user interacts with it. It's a great way to focus the user's attention on a specific task or piece of information. The modal can be closed by clicking a close button, interacting outside the modal, or pressing a key.

Implementing the Modal Window

Let’s dive into the implementation:

document.addEventListener("DOMContentLoaded", function() {
  const modal = document.getElementById("myModal");
  const openBtn = document.getElementById("openModal");
  const closeBtn = document.getElementsByClassName("close")[0];

  openBtn.onclick = function() {
    modal.style.display = "block";
  };

  closeBtn.onclick = function() {
    modal.style.display = "none";
  };

  window.onclick = function(event) {
    if (event.target === modal) {
      modal.style.display = "none";
    }
  };
});
        

Code Explanation

  1. Event Listener for DOMContentLoaded: The script begins by adding an event listener for the DOMContentLoaded event. This ensures that the script runs only after the HTML document has been fully loaded and parsed, making all DOM elements available for manipulation.
  2. Selecting Elements: const modal = document.getElementById("myModal");: This selects the modal element by its ID, myModal. const openBtn = document.getElementById("openModal");: This selects the button that will open the modal. const closeBtn = document.getElementsByClassName("close")[0];: This selects the first element with the class close, which is the close button inside the modal.
  3. Opening the Modal: openBtn.onclick = function() { modal.style.display = "block"; };: This adds an onclick event listener to the open button. When the button is clicked, it sets the modal's display style to block, making the modal visible.
  4. Closing the Modal: closeBtn.onclick = function() { modal.style.display = "none"; };: This adds an onclick event listener to the close button. When the close button inside the modal is clicked, it sets the modal's display style to none, hiding the modal.
  5. Click Outside to Close: window.onclick = function(event) { if (event.target === modal) { modal.style.display = "none"; } };: This adds an event listener to the entire window. If the user clicks anywhere outside the modal content, the modal is closed. This is done by checking if the click event's target is the modal itself.

HTML Structure

Here’s the HTML structure that works with the JavaScript code:

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

<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Modal content here...</p>
  </div>
</div>
        

  • Open Button (#openModal): This button triggers the opening of the modal when clicked.
  • Modal (#myModal): The modal is a div element with the class modal. Inside it, there’s another div with the class modal-content that holds the actual content of the modal, including a close button (<span class="close">&times;</span>) and any other content you want to display.

CSS Styling

Here’s the CSS to style the modal:

.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: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
        

CSS Explanation

  1. Modal Container (.modal): The modal container is initially hidden (display: none). When it’s shown, it covers the entire screen (position: fixed; width: 100%; height: 100%), with a semi-transparent black background (rgba(0,0,0,0.4)).
  2. Modal Content (.modal-content): The modal content is centered within the modal and styled with a white background, padding, and a border.
  3. Close Button (.close): The close button is positioned at the top-right corner of the modal content and styled with a larger font size. It changes color when hovered over or focused.

How It Works

  • When the page loads, the modal is hidden.
  • Clicking the "Open Modal" button triggers the modal to appear by setting its display property to block.
  • The modal remains open until the user either clicks the close button, clicks anywhere outside the modal content, or presses a key (if enhanced for keyboard accessibility).
  • This simple implementation allows you to create reusable modals for various purposes, such as displaying information, capturing user input, or alerting the user.

Conclusion

Creating a modal window using vanilla JavaScript is a straightforward process that requires only a few lines of code. This implementation provides a basic yet functional modal that can be easily customized and integrated into any webpage. By understanding the underlying concepts, you can further enhance this modal with additional features like animations, accessibility improvements, or even converting it into a reusable component in a JavaScript framework.

要查看或添加评论,请登录

社区洞察