Concise Modal Window Built With jQuery And HTML/CSS

File Size: 2.91 KB
Views Total: 928
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Concise Modal Window Built With jQuery And HTML/CSS

You can do a lot with modal windows in web design. They're really useful to get website visitors' attention and use them for any purpose like alert dialogs, login forms, contact forms, etc.

In this tutorial, I'll show you how to use HTML, CSS, and a little bit of jQuery to create a minimal clean modal window that opens on click.

How to use it:

1. Code the HTML for the modal window.

<div class="modal" id="example">
  <div class="inner_modal">
    <div class="modal_content">
      <h1>Modal Title</h1>
      <p>Modal Content</p>
    </div>
  </div>
</div>

2. Create a modal trigger button on the page.

<button 
  open-modal="true" 
  modal-id="example">
  Open Modal
</button>

3. Style the background overlay.

.modal {
  width: 100vw;
  height: 100vh;
  background-color: rgba(16, 16, 16, 0.8);
  position: fixed;
  top: 0;
  z-index: 999;
  display: none;
  opacity: 0;
}

.modal.active {
  display: block;
  opacity: 1;
}

.modal .inner_modal {
  max-height: 100vh;
  box-sizing: border-box;
  display: block;
  overflow-y: auto;
  height: 100%;
  width: 100%;
  padding: 0 20px;
}

4. Style the main content of the modal window.

.modal .modal_content {
  width: 600px;
  max-width: 100%;
  background-color: white;
  display: block;
  margin: 5vh auto;
  padding: 50px;
}

5. Hide the scrollbar when the content is too long, but keep the functionality.

.modal .inner_modal::-webkit-scrollbar {
  display: none;
}

6. Load the necessary jQuery JavaScript library in the document.

<script src="/path/to/cdn/jquery.slim.min.js"></script>

7. Enable the trigger button to open the modal window.

function closeModal(modal) {
  modal.removeClass('active');
}

function openModal(modal) {
  modal.addClass('active');
}

$('*[open-modal="true"]').click(function() {
  var modal = $(this).attr('modal-id');
  openModal($(`.modal#${modal}`));
});

$('.modal').click(function(e) {
  var clickTarget = $(e.target);
  if (clickTarget.attr('class') == 'inner_modal') {
      closeModal(clickTarget.closest('.modal'));
  }
});

This awesome jQuery plugin is developed by marc-hinton. For more Advanced Usages, please check the demo page or visit the official website.