How to change the content of a lightbox

In the first part, we have created lightbox that display a text, a form or an image stored into a <div>. With a JavaScript function we can insert a content dynamically in the box.

Demonstration with a content dynamically changed


Title of the content (image, form or other)
And this is the static content of the box.

Click for the dynamic content...

To display an image in the lightbox, click on the thumbnail of the image...


Changing the content

Command in the onclick event are transferred to a JavaScript file, to be completed with function to load images.
And a set of thumbnails is created on which the user clicks to view the image in the box.

<img src="images/thumb-sea.jpg" width="150" height="150" onclick="openbox('images/small-sea.jpg');">
<img src="images/thumb-vitrage.gif" width="150" height="150" onclick="openbox('images/vitrage.gif');">

The onclick event gives in parameter the URL of the image to display, which corresponds to the thumbnail. This should be generated automatically in use in production.

The JavaScript code:

function openbox(url)
{
  var box = document.getElementById('box'); 
  document.getElementById('filter').style.display='block';
  
  var title = document.getElementById('boxtitle');
  title.innerHTML = url;
  
  var content = document.getElementById('boxcontent');
  content.style.padding="0";
  content.innerHTML = "<img src=" + url + " />";
  box.style.display='block';	
}

Successively are selected:
- The firstbox object for the display, which will be made at the end of the function.
- The title field to assign the name of the image.
- The boxcontent field to put the image

Now that we have a JavaScript file, the HTML file may be simplified by moving the command to close the box into the JavaScript file. Thus, the closebox function is added to:

function closebox()
{
   document.getElementById('box').style.display='none';
   document.getElementById('shadowing').style.display='none';
}

The blox to insert is now so reduced:

<div id="box">
    <div id="boxheader">
        <span id="boxtitle"></span>
        <span id="boxclose" onclick="closebox()"> </span>
    </div>
    <div id="boxcontent"></div>
</div>

Demonstration

The demo is in the archive.

Edition in Wysiwyg mode

In visual mode, the <div> that we insert to build the lightbox can hide the contents of the page.
To avoid this shortcoming, you should add the lightbox code after editing the page. If at a later you change the content of the page in visual mode, the whole block must be temporarily neutralized, for example by putting it into comments with the <!-- --> tags.

© 2008-2014 Xul.fr