How to build a jQuery lightbox!

Today I want to talk about EVERYTHING lightbox. I want to show you how to build your own lightbox using jQuery and CSS. Not only build it but explain to you the road blocks and work arounds any normal developer would run into. We will go over each step on how to make the lightbox work in IE6, IE7 and IE8 as well as all other browsers.

Here is the completed code if you just want to study the little guy.

<!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>Everything You Need to Know About a Lightbox!</title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<style type="text/css">
#lightBox {width:100%; margin:50px 0px; text-align:center; display:none;}
#lightWrap {width:400px; background:#000; border:2px #ccc solid; margin:auto; color:#fff; position:relative;  z-index:2;}
#shade {width:100%; height:100%; position:absolute; top:0px; left:0px; background:#000; -moz-opacity:0.5; -khtml-opacity:0.5; opacity:0.5; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); display:none; z-index:1;}
#closeBox { width:16px; height:16px; line-height:15px; background:#F36; position:absolute; top:5px; right:10px; cursor:pointer;}
</style>
<script>
$(document).ready(function(){
	$("#action").click(function(){
		$("#lightBox").fadeIn("fast");
		if($("body").height() > $("body").offset().height){
				var sH = $("body").height();
			}else{
				var sH = $("body").offset().height;
		}
		$("#shade").css({height:sH+'px',}).slideDown("fast");
		$("#closeBox").click(function(){
			$("#lightBox").fadeOut("fast");
			$("#shade").slideUp("fast");
		});
	});
});
</script>
</head>
<body>
<button id="action">Click Me</button>
<div id="lightBox">
	<div id="lightWrap">
    	<div id="closeBox">X</div>
    	<h2>HELLO This is my very own custom built lightbox!!</h2>
    </div>
</div>
<div id="shade"></div>
</body>
</html>

Thanks Everyone!

This Article's Comments.

  1. 6
    Kyle Says:

    Awesome tut! I’ll be using this soon. Thanks Devin.

  2. 5
    Flo Says:

    Great tutorial! it gets me a closer look to how lightboxes made. The only thing i missed is how to grap the content of the lightbox from another source via ajax. But ok, thats another story i guess

  3. 4
    10V Says:

    Dude, cool tutorial, thanks for sharing!

  4. 3
    Julie Says:

    dude, when do you sleep. this is cool stuff.

  5. 2
    Yogendra Says:

    it is really very cool and great tutorial to learn such kind of stuff quickly
    Thanks alot Devin.

    Keep it up!!!!!!!!!

  6. 1
    Devin R. Olsen Says:

    I always enjoy feedback from my readers!

Leave a Reply