Home Uniquely NZ Travel Howto Pauline Small Firms Search
Web Site Design
Using Lightbox to Display Web Images

Settings - opens in a new window or tab

The Howto Article on Popup Windows for Images and the enhancements covered in Advanced JavaScript Popup Windows for Images have been some of of the most popular articles I wrote and I got a lot of useful feedback. What I set out to do was to be able to have a number of thumbnails (icons) on a page which open in a single correctly sized 'popup' Window when they were clicked and then remain in the background when one continued to browse down the page. If clicked again the window should return to the same place in the foreground or if another image is clicked it should replace the previous image and again return to the same place in the foreground. You would think this would be a common requirement and somebody would have implemented it using JavaScript. Surprisingly I could not find any proper examples of this to copy. My searches provided plenty of examples of opening Windows once for images but none which worked correctly when reusing the Window for the same or a new image and brought it back to be in view so I was forced to write my own or to be more correct a series of such popup handlers of increasing complexity as my requirements increased and other people asked me for various enhancements which were covered in Advanced JavaScript Popup Windows for Images which features Popup windows which will resize for different images, allow titles to be displayed and the background colour specified. Those are the ones that are used extensively on our web site.

You can switch to popup mode using the links in the box at the top or at the bottom of this page if you have a Netbook, Laptop or Desktop with a screen size of over 1024 x 600 to see the end result. If you have a smaller screen my current software forces use of the lightbox style and these links are hidden.

As you will be able to see above, popup windows work very well with a reasonable size screen and an operating system/browser supporting multiple windows. On such a system it is difficult to beat and I have used it extensively on my web site where there are over 5000 images using it and it has been tested over a long period on Windows, Linux and Apple machines in many different browsers including Internet Explorer, Firefox, Opera, Chrome and Safari.

However they do not work well on the modern Smart Phones and Tablets with small screens and are based round a tabbed approach rather than implementing separate windows. This makes the approach very clumsy as every popup is opened in a new tab and the reloading and automatic closing does not work. The alternative is an approach with has tended to be called Lightbox which is a JavaScript technique used to display images and other web content using modal windows where the image is overlayed over the screen with the surround dimmed out. The overlayed window can be closed by clicking outside of it or by a close button usually a standard crosscross. Ideally the image should display full size when there is space available and shrink to fit the space available. Lightbox was originally the name of a specific JavaScript plugin, written by Lokesh Dhakar. However, common usage of the term has evolved to encompass Lightbox-style JavaScript plugins and such effects in general. The technique is now used very widely because of its simple yet elegant style and easy implementation and, most importantly it works well on small screens. The disadvantage is that it blocks use of the main window whilst a popup can just be moved aside but still be visible. The same images are below so you can contrast the approaches. I am using the original Lightbox initially but many of the implementations allow one to show video, web content etc in addition to just pictures and even run slide shows.

You will see that the two sets of pictures are in different 'Galleries' and one can move in the overlay backwards and Forwards within the two Galleries. This is a major feature of Lightbox which can not be implemented in my Popup Window method. There is an option to allow them to roll round

It proved very easy to install Lightbox to make my initial tests. One just needs to download a zipped file from Lokesh Dhakar's Lightbox2 Site and extract 3 folders which need to be uploaded to the root of the web site. Read the latest instructions carefully!

NOTE: I have never bothered to update these to the latest versions so mine is from old version 2.7.1 released 30 March 2014 and that is what all my tests have used up to November 2019. If you have problems go back and try that version! Otherwise use latest versions which avoid various issues with recent windows browsers and also have a single .js file with Jquery included for those not already using it..

NOTE: Later versions require a major change in layout with <script src="path/to/lightbox.js"></script> at BOTTOM OF PAGE before the closing </body> instead of being in head as shown here.

Each html file which has pictures using Lightbox to display needs three lines added to them head section after which there is just a single ' call' required for each picture - a thumbnail and a full image are required.

A typical head section with the three lightbox links in red for version 2.7.1 and lower looks like:

<!DOCTYPE html>
<html lang="en-GB">

<head>
<meta charset="utf-8">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/lightbox.min.js"></script>
<link rel="stylesheet" href="css/lightbox.css">

<link rel="stylesheet" href="responsive.css">
<script src="rbox.js" ></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Dr P Curtis">
<meta name="description" content="Technical Support Article covering Mobile Friendly Responsive web site design">
<meta name="keywords" content="responsive, web, design, lightbox, mobile, Mobile First, Mobile Friendly, Responsive Web Design">
<title>Responsive Web Design</title>
</head>

Note the links to my own JavaScript and CSS files follow the jQuery and Lightbox links and the order of those links is also important.

Also Note that the above is for HTML5 ( <!DOCTYPE html>, <html lang="en-GB"> and <meta charset="utf-8"> statements) - Lightbox works better with HTML5.

A typical direct call looks like:

<a href="img/img_1234b.jpg" data-lightbox="attribute1" data-title="caption1"><img="2015/img_1234i.jpg style="width:160px;height:120:px;float:left;" alt="caption1" title="caption1"></a>

One just needs to add a data-lightbox attribute to any image link to activate Lightbox. If multiple images have the same data-lightbox attribute they are displayed as a set and one can move backawards and forwards through the set and the next and previous images are preloaded. The data-title is optional and displays a caption below the image.

The majority of images on my pages are standardised in size (160 x 120 thumbnails for 400 x300 or 600 x 400 full size popup/lightbox images) and inserted by a JavaScript function which dynamically writes on-the-fly the full HTML code into the page. This is because the code is very repetative and the only information specific to each image is the image , title and alighnment (floated left or right or centered in a table cell) so a typical call would be

<script>hpop('2015/img_1234.jpg', 'Picture copyright P Curtis 2015', 'left')</script>

It initially looked as if the 'script calls' I use for my popups could remain the same and only the JavaScript function would need to be changed. This would mean the the changes on most of my pages would be small and most could be made by a couple of 'find and replace' edits. This seemed to work until I tested the shrinking to fit small windows as would be used on a mobile device an I found that feature seemed to required HTML 5 to work. I changed the Doctype so the page was set to use HTML 5 and everything seemed to be work in the usual browsers but when I came to validate the page the differences between HTML5 and HTML 4.01 Transient became more obvious. My fairly simple test page generated 57 HTML errors, and that did not include the dynamically written text for the popup calls which the validator did not see!

Now lets have a look at what this all means. First we need a way to choose between popups and lightbox displays - this is via an extra cookie called pref_box . We also need to force a lightbox display if we do not have a Desktop, Laptop or Netbook ( isComputer() and isNetbook() functions ). We can then use the existing code for hpop() and vpop() or call the new functions hbox() and vbox() to write 0n-the-fly to the page.

hbox() and vbox() have been written from the start to write HTML5 compatible code to the page so make extensive use of css.


function hbox(image, title, alignment) {
  cssalign = "width: 160px; height:120px; display: block;margin-left:auto;margin-right:auto;padding-left:6px;padding-right:6px;padding-top:10px;padding-bottom:10px;"
  if(alignment == "left"){ cssalign = "width: 160px; height:120px;float:left;padding-left:0px;padding-right:6px;padding-top:10px;padding-bottom:10px;" ; alignment="center"};
  if(alignment == "right") { cssalign = "width: 160px; height:120px; float:right;padding-left:6px;padding-right:0px;padding-top:10px;padding-bottom:10px;" ; alignment="center"}
  if((alignment !== "center" && alignment.substring(0, 7) !== "gallery") || getCookie('broadband') == "false" ){alignment = image.substring(image.lastIndexOf('/')+1) };
  title = title + " (" + image.substring(image.lastIndexOf('/')+1) + ")";
    document.write('<a href=\"' + image + 'b.jpg\" data-lightbox=\"' + alignment + '\" data-title=\"' + title +'\"><IMG src= \"' +image + 'i.jpg\" alt=\"' + title + '\" title=\"' + title + '\" style=\" ' + cssalign + ' \" \/></a>')
}

function vbox(image, title, alignment) {
  cssalign = "display: block; margin-left: auto; margin-right: auto;"
  if(alignment == "left"){ cssalign = "float:left;" ; alignment="center"};
  if(alignment == "right") { cssalign = "float:right;" ; alignment="center"}
  if((alignment !== "center" && alignment.substring(0, 7) !== "gallery") || getCookie('broadband') == "false" ){alignment = image.substring(image.lastIndexOf('/')+1) };
  title = title + " (" + image.substring(image.lastIndexOf('/')+1) + ")";
  document.write('<a href=\"' + image + 'b.jpg\" data-lightbox=\"' + alignment + '\" data-title=\"' + title + ')' +'\"><IMG src= \"' +image + 'i.jpg\" alt=\"' + title + '\" title=\"' + title + '\" style=\"width: 120px; height:160px; padding-left:6px;padding-right:6px;padding-top:10px;padding-bottom:10px; ' + cssalign + ' \" \/></a>')
}

The alignment parameter has to be compatible with earlier use where the only three valid value were left, right and center. Now only left and right are used for single images which are floated left and right with text wrapping round them. If alignment is center or starts with gallery it is passed as the data-lightbox parameter unless the cookie broadband is false. This allows groupings of images into galleries which involves preloading of pictures. Pre loading is inhibited by making each parameter passed to data-lightbox unique by changing it to the image filename. The image filename is also added to the title. Single images are included in the 'center' gallery.

We also need to modify thee functions hpop() and vpop() (which were comprehensively covered in the previous article in the series Advanced JavaScript Popup Windows for Images) to use css if we are going to make them HTML5 compatible. The resulting HTML5 compatible code with the choice of handing off to hbox() and vbox() is:

Functions to put in the HTML to provide simplified calls for vertical and horizontal popups with a doubleClick event handler calling toggle() so that large popups can be displayed if user has broadband. image parameter must be 8 or more characters. Three pictures expected imagei.jpg imagew.jpg and imageb.jpg (160px, 400px and 600px). Alignment can be left|right|center|galleryxxxx - other value are taken to be center. The image filename is displayed in the title. The display can be handed off to a compatible lightbox display function.
*/

var cssalign = "" ;
function hpop(image, title, alignment) {
  if ( getCookie('pref_box') == "true" || !( isComputer() || isNetbook() ) || isIE9() ) {
    hbox(image, title, alignment)
  } else {
    cssalign = "display: block; margin-left: auto; margin-right: auto;"
    if(alignment == "left"){ cssalign = "float:left;"};
    if(alignment == "right") { cssalign = "float:right;"};
    title = title + " (" + image.substring(image.lastIndexOf('/')+1) + ")";
    document.write('<IMG src= \"' +image + 'i.jpg\" alt=\"' + title + '\" title=\"' + title + '\" style=\"width: 160px; height:120px; padding: 10px; ' + cssalign + ' \" onDblClick=\"toggle()\" onClick=\"popitup2h(\' ' + image + '\' ,\' ' + title + ' \' )\" \>')
  }
}

function vpop(image, title, alignment) {
  if ( getCookie('pref_box') == "true" || !( isComputer() || isNetbook() ) || isIE9() ) {
    vbox(image, title, alignment)
  } else {
    cssalign = "display: block; margin-left: auto; margin-right: auto;"
    if(alignment == "left"){ cssalign = "float:left;"};
    if(alignment == "right") { cssalign = "float:right;"}
    title = title + " (" + image.substring(image.lastIndexOf('/')+1) + ")";
    document.write('<IMG src= \"' +image + 'i.jpg\" alt=\"' + title + '\" title=\"' + title + '\" style=\"width: 120px; height:160px; padding: 10px; ' + cssalign + ' \" onDblClick=\"toggle()\" onClick=\"popitup2v(\' ' + image + '\' ,\' ' + title+ ' \' )\" \>')
  }
}

Finally we need to change function popup5() to use css if we are going to make all the code writen-on-the-fly HTML5 compatible

// Routine for popup windows with title, size and background colour parameter (5 parameters).
// Modified 18 June 2015 to uses css and be HTML5 compatible.

var newwindow;
var wheight = 0, wwidth = 0;
function popitup5(url, title, iwidth, iheight, colour) {
var pwidth, pheight;
if (isOpera() ) {if (newwindow && !newwindow.closed) { newwindow.close(); }} // Opera fudge - every window is new
if ( !newwindow || newwindow.closed ) {
pwidth=iwidth+30;
pheight=iheight+70;
newwindow=window.open('','htmlname','width=' + pwidth +',height=' +pheight + ',resizable=yes,top=50,left=10,status=no,location=no');
wheight=iheight;
wwidth=iwidth;
}
if (wheight!=iheight || wwidth!=iwidth ) {
pwidth=iwidth+30;
pheight=iheight+70;
if (window.resizeTo) newwindow.resizeTo(pwidth, pheight);
wheight=iheight;
wwidth=iwidth;
}
newwindow.document.clear();
newwindow.document.writeln('<html> <head> <title>' + title + ' <\/title> <\/head> <body style= \"background-color:' + colour + ';\"><div style=\"text-align:center;\">');
newwindow.document.writeln('<img src=' + url + ' title=\"' + title + '\" alt=\"' + title + '\" >')
newwindow.document.writeln('<\/div> <\/body> <\/html>');
newwindow.document.close();
if (is_chrome) {newwindow.parent.blur();} // Chrome focus workround
newwindow.focus();
}

I decided to continue with carrying out the changes to the pages with scripted calls to images which involved adding three lines and changing the two links to use a different Javascript and css file in the <head> section and progressively change to HTML5 on the web pages to realise their full potential on mobiles.

Lightbox Options

Lightbox has a few useful options including the ability to make the click through 'slide shows' loop back to the start. One is supposed to put the options in a script statement but I did not make that work and edited them into the .js file. This is in a compacted version but it is possible to search for them if you know the names for his documentation.

The Elephant in the Room - HTML5

As can be seen above the changes to provide an option to use lightbox image displays instead of popup windows is largely restricted to the single script file with only a few lines to insert in the head and a couple of links to change. In addition I considered it desirable to add options for changing the settings to the pages by cut and pasting a new footer.

There is a big However - Lightbox seems to work best with HTML5. This page, even before it got to this length generated 57 errors when revalidated against HTML5 , and that did not include the dynamically written text for the popup calls!

This has forced me up a learning curve on HTML 5 and the discovery of several tricks before I could replace all the depreciated and unsupported elements (tags) and attributes from HTML 4.01 where I was using the undemanding Transitional specification. I will document the Switch to HTML5 on a separate page but note here that the template pages took an hour or more each to change and validate whilst the subsequent travelogues which tend to be in groups could be modified in 15 minutes or so. This is still a daunting task with 800 pages although I am sure that more familiarity enables me to make the changes from attributes to css more quickly and more will end up in the 'master' css included file.

Link to W3C HTML5 Validator Copyright © Peter & Pauline Curtis
Fonts revised: 28th April, 2021