Skip to content

Instantly share code, notes, and snippets.

@matkl
Created January 10, 2014 00:22
Show Gist options
  • Save matkl/8344711 to your computer and use it in GitHub Desktop.
Save matkl/8344711 to your computer and use it in GitHub Desktop.
Lightbox for IE9+, Chrome, Firefox.
.lightbox {
background: rgba(0,0,0,0.85);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
}
.lightbox img {
position: absolute;
top: 50%;
left: 50%;
}
window.addEventListener('load', function(event) {
var nodes = document.querySelectorAll('a[rel="lightbox"]');
Array.prototype.forEach.call(nodes, function(node) {
node.addEventListener('click', function(event) {
var lightbox = document.createElement('div');
lightbox.className = 'lightbox';
lightbox.style.overflow = 'hidden';
lightbox.addEventListener('click', function(event) {
document.body.removeChild(lightbox);
});
var img = document.createElement('img');
img.src = node.href;
img.addEventListener('load', function(event) {
lightbox.style.overflow = '';
img.style.visibility = '';
img.style.marginTop = -img.offsetHeight/2 + 'px';
img.style.marginLeft = -img.offsetWidth/2 + 'px';
});
lightbox.appendChild(img);
img.style.visibility = 'hidden';
document.body.appendChild(lightbox);
event.preventDefault();
});
});
});
<html>
<head>
<script src='lightbox.js'></script>
<link href='style.css' rel='stylesheet' />
</head>
<body>
<a href='http://lorempixel.com/800/600/' rel='lightbox'>Photo 1</a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment