How To Create A Lightbox To Display Text Or Images

May 28, 2009

Here is most simple way to code a Lightbox, just under 55 lines of HTML and JavaScript code.

Few comments about the code:

JavaScript

Function displayHideBox(boxNumber) used for opening and closing lightbox, boxNumber parameter is for multiple light boxes on the page. Just change a number in div id id="LightBox1" and then use this number to open and close this box onclick="displayHideBox('1');”

Styles

.grayBox – for the gray background. You can play with opacity to make it lighter or darker

.box_content – for the white box. You can play with positions and padding to fit it to your design.

HTML

In order to place an image into the box, or change the text inside do it after <!-- Box content --> comment.

Samples

http://www.laptopsbuyer.ca/getQuote/ - Help links next to Model, Screen Size and Condition open light boxes

http://www.easysmsreminder.com/ - Terms and Conditions in the registration form (Instead of close X on top of the box, I Agree or Cancel used to close the box and check checkbox if user agrees)

Code (From File: http://superiorwebsys.com/blog/posts/lightBox.php)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Light Box</title>
<script type="text/javascript" language="javascript">
/* Superior Web Systems */
function displayHideBox(boxNumber)
{
    if(document.getElementById("LightBox"+boxNumber).style.display=="none") {
        document.getElementById("LightBox"+boxNumber).style.display="block";
        document.getElementById("grayBG").style.display="block";
    } else {
        document.getElementById("LightBox"+boxNumber).style.display="none";
        document.getElementById("grayBG").style.display="none";
    }
}
</script>
<style>
.grayBox{
    position: fixed;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}
.box_content {
    position: fixed;
    top: 25%;
    left: 30%;
    right: 30%;
    width: 40%;
    padding: 16px;
    z-index:1002;
    overflow: auto;
}
</style>
</head>
<body>
<div id="grayBG" class="grayBox" style="display:none;"></div>
<div id="LightBox1" class="box_content" style="display:none;">
<table cellpadding="3" cellspacing="0" border="0">
  <tr align="left">
    <td colspan="2" bgcolor="#FFFFFF" style="padding:10px;"><div onclick="displayHideBox('1'); return false;" style="cursor:pointer;" align="right">X</div><p><!-- Box content -->Text of the box!!!</p></td>
  </tr>
</table>
</div>
<a href="#" onclick="displayHideBox('1'); return false;">Open Box</a>
</body>
</html>

Michael Pankratov