Last active
August 29, 2015 14:22
-
-
Save hkfoster/27327357bed5e5c4852a to your computer and use it in GitHub Desktop.
A Simple Lightbox Trigger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Lightbox.js 0.0.1 | |
* @author Kyle Foster (@hkfoster) | |
* @license MIT (http://www.opensource.org/licenses/mit-license.php/) | |
*/ | |
var lightBoxInit = ( function() { | |
var triggers = document.querySelectorAll( '[rel="modal"]' ); | |
if ( triggers ) { | |
var init = function() { | |
// Assignment | |
var modals = document.querySelectorAll( '.modal' ), | |
overlay; | |
// And add an overlay to modal elements | |
for ( var modalIndex = 0; modalIndex < modals.length; modalIndex++ ) { | |
addOverlay( modals[ modalIndex ] ); | |
} | |
// Attach event listeners to trigger elements | |
for ( var triggerIndex = 0; triggerIndex < triggers.length; triggerIndex++ ) { | |
triggers[ triggerIndex ].addEventListener( 'click', showModal, false ); | |
} | |
// Add overlay function | |
function addOverlay( parentNode ) { | |
// Create overlay element | |
overlay = document.createElement( 'span' ); | |
// Attribute assignment | |
classie.add( overlay, 'overlay' ); | |
overlay.title = 'Close this modal'; | |
// Append to modal | |
parentNode.appendChild( overlay ); | |
} | |
// Show modal function | |
function showModal( event ) { | |
// Prevent default behavior/bubbling | |
event.stopPropagation(); | |
event.preventDefault(); | |
// Assignment | |
var targetModal = document.querySelector( '#' + this.href.split( '#' )[ 1 ] ); | |
overlay = targetModal.querySelector( '.overlay' ); | |
// Add overlay click event listener | |
overlay.addEventListener( 'click', hideModal, false ); | |
// Show the modal | |
classie.add( targetModal, 'visible' ); | |
// Kill scrolling behind modal | |
classie.add( document.body, 'no-scroll' ); | |
} | |
// Hide modal function | |
function hideModal() { | |
// Assignment | |
var visibleModal = document.querySelector( '.modal.visible' ); | |
// Hide the modal | |
classie.remove( visibleModal, 'visible' ); | |
// Remove overlay click event listener | |
overlay.removeEventListener( 'click', hideModal, false ); | |
// Empty variable to prevent bubbling | |
overlay = null; | |
// Turn scrolling back on | |
classie.remove( document.body, 'no-scroll' ); | |
} | |
}; | |
init(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment