Search This Blog

Tuesday, October 13, 2009

Lightbox2 + Images + Automatic Scaling = Yay!

Recently I had the quick need for a floating image javascript and stumbled over Lightbox2. It's really easy to include in a web site and makes nice floating images with 'back' and 'next' buttons and smooth resizing between images.

However, the one feature that came up (and I found I'm not the first one with that need) is limiting the image size to something reasonable. So I've tweaked the code for the imgPreloader a bit to allow me to set a maxWidth and maxHeight property in the LightboxOptions.


imgPreloader.onload = (function(){
this.lightboxImage.src = this.imageArray[this.activeImage][0];

var imgwidth = imgPreloader.width;
var imgheight = imgPreloader.height;

if( LightboxOptions.maxWidth ) {
if( imgwidth > LightboxOptions.maxWidth ) {
var factor = imgwidth / LightboxOptions.maxWidth;
imgwidth = LightboxOptions.maxWidth;
imgheight = imgheight / factor;
this.lightboxImage.setStyle({
width: '' + imgwidth + 'px',
height: '' + imgheight + 'px'
});
}
}

if( LightboxOptions.maxHeight ) {
if( imgheight > LightboxOptions.maxHeight ) {
var factor = imgheight / LightboxOptions.maxHeight;
imgheight = LightboxOptions.maxHeight;
imgwidth = imgwidth / factor;
this.lightboxImage.setStyle({
width: '' + imgwidth + 'px',
height: '' + imgheight + 'px'
});
}
}

this.lightboxImage.width = imgwidth;
this.lightboxImage.height = imgheight;
this.resizeImageContainer(imgwidth, imgheight);
}).bind(this);

No comments: