Lightbox2: Limit the max image size

Lightbox2 is a JavaScript technique used to display a high resolution image in a modal dialog while the rest of the website is darkened.

Unfortunately the original code of Lightbox2 shows the image with its full size. This means if an image is twice as big as your browser window you’ll see it it partly and you must scroll to see the other part. This effect is shown in the following image.

nailbox3

How to fix this

Most probably this is not what you want but to display it with a limited width and height. This is easy to achieve even if you’re not a programmer. Somewhere on your hard drive you should have the file lightbox.js. Open this file and go to line 205 (as of version 2.05) and replace the following code section.

To be replaced:

preloader.onload = function() {
  
  $image.width = preloader.width;
  $image.height = preloader.height;
  $image.attr('src', _this.album[imageNumber].link);
  
  return _this.sizeContainer(preloader.width, preloader.height);
};

New code:

preloader.onload = function() {
  
  var maxwidth = 800;

  if(preloader.width > maxwidth)
  {
    var scale = preloader.width / maxwidth
    preloader.width = maxwidth;
    preloader.height = preloader.height /scale;
    $image.css("maxWidth", maxwidth + "px");
  }  

  $image.width = preloader.width;
  $image.height = preloader.height;
  $image.attr('src', _this.album[imageNumber].link);

  return _this.sizeContainer(preloader.width, preloader.height);
};

That’s it

No css file needs to be changed, after the replacement you’re really done and the result looks as to what we initially wanted.

nailbox2

Get it

Instead of applying the above hack yourself you can download Lightbox2 with the patch already included.

Either use the direct download link or one of the following commands.

git clone git://github.com/slopjong/lightbox2.git
wget http://github.com/slopjong/lightbox2/archive/v2.05-maxwidth.zip
wget http://github.com/slopjong/lightbox2/archive/v2.05-maxwidth.tar.gz

8 Comments

  1. Thanks for that works nice.

  2. Thanks a Lot !! It rocks…!

  3. OMG ! Thx you so much !

  4. Thank you so much, it works perfectly!

  5. heh

    Hi,
    your code is not working.

  6. slopjong

    @heh, can you make it work for you and share your solution? Thanks.

  7. trco

    Thx very much … veeeery good

  8. Yossi

    This looks like a great solution.
    However, we use the lightbox adaption “slimbox” and I don’t find similar code there.
    Do you know the same type of fix in slimbox?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>