Author: | wisd81 |
---|---|
Views Total: | 79,329 views |
Official Page: | Go to website |
Last Update: | March 7, 2016 |
License: | MIT |
Preview:

Description:
A simple, lightweight vanilla JavaScript library that lets you create a modal window while blurring the background content to focus your user’s attention on modal content.
How to use it:
The html structure for the modal window.
<div id="myModal" class="Modal is-hidden is-visuallyHidden"> <!-- Modal content --> <div class="Modal-content"> <span id="closeModal" class="Close">×</span> <p>Simple Modal</p> </div> </div>
Create a toggle button to open the modal window.
<button id="myBtn">Open Modal</button>
The main CSS styles for the modal window.
.Modal { display: block; position: fixed; left: 0; top: 0; z-index: 9999; width: 100%; height: 100%; padding-top: 100px; background-color: black; background-color: rgba(0, 0, 0, 0.4); -webkit-transition: 0.5s; overflow: auto; transition: all 0.3s linear; } .Modal-content { background-color: #fefefe; margin: auto; padding: 20px; border-radius: 4px; max-width: 300px; height: 450px; } .ModalOpen { overflow: hidden; } .is-hidden { display: none; } .is-visuallyHidden { opacity: 0; }
Style and position the modal close button.
.Close { color: #aaaaaa; float: right; font-size: 16px; } .Close:hover, .Close:focus { color: #000; text-decoration: none; cursor: pointer; }
Blur the main content using CSS3 filters.
.is-blurred { filter: blur(2px); -webkit-filter: blur(2px); }
The main JavaScript.
// Get the modal var modal = document.getElementById('myModal'); // Get the main container and the body var body = document.getElementsByTagName('body'); var container = document.getElementById('myContainer'); // Get the open button var btnOpen = document.getElementById("myBtn"); // Get the close button var btnClose = document.getElementById("closeModal"); // Open the modal btnOpen.onclick = function() { modal.className = "Modal is-visuallyHidden"; setTimeout(function() { container.className = "MainContainer is-blurred"; modal.className = "Modal"; }, 100); container.parentElement.className = "ModalOpen"; } // Close the modal btnClose.onclick = function() { modal.className = "Modal is-hidden is-visuallyHidden"; body.className = ""; container.className = "MainContainer"; container.parentElement.className = ""; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.className = "Modal is-hidden"; body.className = ""; container.className = "MainContainer"; container.parentElement.className = ""; } }
Works brilliantly. Thank you so much.
When I try to run this, I get the following errors:
Uncaught TypeError: Cannot read property ‘parentElement’ of null
Uncaught TypeError: Cannot set property ‘className’ of null
What am I missing here?
I have the same issue.
Thanks for the Code, After using this one my site becomes pro