Home Pauline Howto Articles Uniquely NZ 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.

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. 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 looks like:

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

<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>

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 ) {
newwindow=window.open('','htmlname','width=' + pwidth +',height=' +pheight + ',resizable=yes,top=50,left=10,status=no,location=no');
if (wheight!=iheight || wwidth!=iwidth ) {
if (window.resizeTo) newwindow.resizeTo(pwidth, pheight);
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>');
if (is_chrome) {newwindow.parent.blur();} // Chrome focus workround

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.

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 600 pages although I am sure that more familiarity will enable me to make the changes from attributes to css more quickly and more will end up in the 'master' css included file.

Home Pauline Howto Articles Uniquely NZ Small Firms Search
Copyright © Peter and Pauline Curtis
Content revised: 26th August, 2015