Image Viewer

Lightbox-style image viewer script, where clicking a thumbnail or text link opens a large image.

Browser support

Tested to work in IE9, IE11 and 2015 versions of Firefox and Chrome in Windows.

The script may be a bit buggy in mobile browsers, especially if you change orientation.

Degrades gracefully as ordinary image links in older browsers, or if JavaScript is not used.


See the photography page, where this script is used. Due to a few bugs, the image viewer is normally disabled in mobile browsers. If you still want to test the image viewer in mobile browsers, open the photography page with this alternate link.

To detect mobile browsers, the script looks for the the word mobi in the User Agent String (but in general I advice against UA string sniffing, see for example MDN - Browser detection using the user agent).

How it works

The script opens the image viewer on any clicked link with class="thumbnail". The linked image is displayed in its natural size or made smaller to fit inside the browser viewport.

Hovering the enlarged image brings up buttons for moving to the next or previous image, and for closing the image viewer. You can also close by clicking the darkened area around the enlarged image. Keyboard navigation is supported (only tested in Windows so far): the Left and Right arrow keys change image, and the Esc key closes the image viewer.

Thumbnail preloading

No image preloading is done in the script itself. Because of this the image viewer may actually work less well if you use smaller thumbnail image files for the links (as is traditionally recommended for thumbnail galleries), since the script then can't load any of the large image files until just before they're needed (such as when clicking a Next or Previous button). This would cause a delay for every single large image the user wants to see.

If you instead use the same full size image files in the thumbnail links (made smaller with CSS) as in the image viewer, all of them can already be preloaded by the browser when the image viewer is opened, while users with a slow Internet connection will at least get a visual indication on how far the image loading has progressed.

published: Nov 7, 2015
last modified: Jan 26, 2017