jQuery lightbox plugin
posted on November 7, 2015, 12:00 am in
code
jQuery.fn.lightbox = function() {
var close = function() {
$('.ui-lightbox').fadeOut(500, function () {
$('.ui-backdrop, .ui-backdrop-light').fadeOut(200, function () {
$(this).remove();
$(document).off('keydown');
$(window).off('resize');
});
});
};
var resize = function(event) {
var maxw = ($(window).width() - 75 < 100) ? 100 : $(window).width() - 75,
maxh = ($(window).height() - 75 < 100) ? 100 : $(window).height() - 75,
height = event.data.height,
width = event.data.width,
ratio = maxh / maxw;
if (height / width > ratio) {
if (height > maxh) {
width = Math.round(width * (maxh / height));
height = maxh;
}
} else {
if (width > maxw) {
height = Math.round(height * (maxw / width));
width = maxw;
}
}
$('.ui-lightbox > img').attr({ width: width, height: height });
$('.ui-lightbox').css({ 'width': width, 'height': height });
};
var open = function(a) {
$('body').prepend('<div class="ui-backdrop"><div class="ui-lightbox"><a class="ui-lightbox-close">×</a>Loading...</div></div>');
$('.ui-close').click(function(e) {
e.preventDefault();
close();
});
var img = new Image();
img.onload = function() {
$('.ui-lightbox')
.empty()
.append('<a class="ui-lightbox-close" href="#">×</a>')
.append('<img src="' + img.src + '" alt="" width="' + this.width + '" height="' + this.height + '" />');
$('.ui-backdrop, .ui-lightbox-close').click(function(e) {
e.preventDefault();
close();
});
$(window).on('resize.cssui', {
width: this.width,
height: this.height
}, resize);
$(window).trigger('resize.cssui');
};
img.src = $(a).attr('href');
$('.ui-backdrop, .ui-backdrop-light').fadeIn(250, function () {
$('.ui-lightbox').fadeIn(100);
});
$(document).on('keydown', function (e) {
switch (e.which) {
case 37: console.log("left"); break;
case 39: console.log("right"); break;
case 27: console.log("esc"); close(); break;
}
return false;
});
};
$.each($(this), function(a, k) {
$(k).click(function(e){ e.preventDefault(); open(k); });
});
return this;
};
.ui-backdrop{
position: fixed;
width: 100%;
height: 100%;
display: none;
background: rgba(0,0,0,.6);
background: -webkit-gradient(radial, center center, 0, center center, 950, from(rgba(0,0,0,.3)), to(rgba(0,0,0,.6)));
top: 0;
left: 0;
z-index: 998;
}
.ui-lightbox{
width: 450px;
position: relative;
display: none;
margin: 50px auto;
background-color: black;
padding: 0px;
z-index: 999;
-webkit-box-shadow: 0px 0px 25px rgba(0,0,0,.6);
-moz-box-shadow: 0 0 25px rgba(0,0,0,.6);
box-shadow: 0 0 25px rgba(0,0,0,.6);
}
.ui-lightbox-close{
text-decoration: none;
position: absolute;
text-shadow: 0px 0px 1px #7a7a7a;
color: white;
top: 0px;
right: 10px;
width: 25px;
height: 25px;
font-size: 38px;
opacity: 0.2;
}
.ui-lightbox-close:hover{
opacity: 1;
}
usage
Run with
$('a.lightbox').lightbox();
Check out the fiddle: jsfiddle.net/j6hsw2et/