Kilian Valkhof

Building tools that make developers awesome.

Building your own lightbox – part 1

Javascript, 23 July 2008, 5 minute read

A lightbox is a way of showing an image, a movie or an entire web page as an overlay on a website. It is often used in gallery style websites and for portfolio’s. This article will look into the basics of building your own lightbox for images.

Part 2, published next week, will look into some of the cooler stuff:

Why an article on making a lightbox?

I know, I know, there are a lot of really good lightbox scripts out there already (check out the comparison matrix!) However, during my internship I developed a website that needed some very specific lightbox effects, and none of the existing lightbox scripts did what I wanted them to do. It was really fun to build one on my own, so I thought I’d let you share in the excitement ;)

Let’s get started!

Whenever I develop something, I first take a couple of steps back and make a list of all the actions that I need to perform that together make the complete effect I want to achieve.

The actions that happen when opening a lightbox:

  1. User clicks on a link designated as a lightbox link
  2. A Javascript event handler picks up on it
  3. Two extra elements get added into the DOM:
    • A 100% width and 100% height overlay
    • A container for the image/movie/page getting loaded
  4. overflow-y:hidden gets added to the body to prevent scrolling
  5. An ajax call is made to retrieve the href of the link
  6. Javascript makes the loaded content visible and positions it as soon as it’s loaded
  7. The Javascript does a return false to make sure the regular link doesn’t fire as well

jQuery, the library I used to develop the lightbox, makes it trivially easy, so lets start. Throughout the article, we’ll be working with this link:

<a href="" class="lightbox">open lightbox!</a>

1. The event handler

$(".lightbox").click(function() {

“Find the elements with class “lightbox”, and if someone clicks on one of them, execute the function window.startOverlay.”

The only problem with the code above is that I don’t specify which link gets clicked. So we have to get the contents of the href attribute and send it along as a parameter:

	overlayLink = $(this).attr("href");

2. Get the DOM ready

As I said in the list above, I need two new elements, and i need to prevent the viewport from scrolling.

function startOverlay(overlayLink) {
		.append('<div class="overlay"></div><div class="container"></div>')

Now all the needed elements are in the DOM and ready to be used. However, the newly made elements have no style yet, so we need to add some CSS to our stylesheet:

.overlay {
.container {

The two odd things here are the fact that all opacity is set to zero, and that .container is way, way to the left. That is because the actual content hasn’t loaded yet, so we just hide it all for now.

We need to make the semitransparent overlay visible however, and for that we use a fade. (You can use any other animation too, but the fade-in just looks the best, IMO);

function startOverlay(overlayLink) {
	$(".overlay").animate({"opacity":"0.6"}, 200, "linear");

This tells jQuery to animate the opacity from the current value (zero) to 0.6, do so in 200 milliseconds, and have a linear transitions (part 2, next week, will look into some of the other possible transitions)

After this has happened, we need to load in the content to put in the lightbox.

3. The Ajax call

I’ll tell you a little secret. For the loading of an image, You don’t actually need an ajax call! You just add the image to the DOM and your browser downloads it automatically.

The “Ajax” bit is just this:

function startOverlay(overlayLink) {
	$(".container").html('<img src="'+overlayLink+'" alt="" />');

The overlayLink is the link of the clicked element that we added into the function as a parameter when someone clicks a link. It doesn’t work like this with web pages, but we’ll write something for that, next week.

4. Make it visible

We now have everything set for the grande finale: actually displaying the image!

We need only a little information: the width and height of the image. Then we position the container in the middle of the screen, and fade it in. However, we can’t just request it, It might still be downloading and then we get the wrong or no dimensions at all. So before doing anything, we need to check whether it has downloaded completely, and only then request the dimensions. Luckily, that is fairly easy:

function startOverlay(overlayLink) {
	$(".container img").load(function() {
		var imgWidth = $(".container img").width();
		var imgHeight = $(".container img").height();
				"top":        "50%",
				"left:        "50%",
				"width":      imgWidth,
				"height":     imgHeight,
				"margin-top": -(imgHeight/2),
				"margin-left":-(imgWidth/2) //to position it in the middle
			.animate({"opacity":"1"}, 200, "linear");

The load function get executed as soon as the image has loaded fully. When the image is loaded, we get the right dimensions, position the image and, last but not least, make the image available with a nice fade.

5. return false;

Now that everything is successful, and you have a working lightbox, you just need to do one last thing: make sure the browser doesn’t also load the link itself!

$(".lightbox").click(function() {
	return false;


That’s it, now we’re done. We have a working lightbox and all our users are happy.



Allowing the user to close the lightbox.

Of course, a user must be able to close an lightbox as well. This usually happens when someone clicks next to the image, so we’ll take that method for now. (We’ll expand on it in part 2.) The actions for closing a lightbox:

If you’ve stuck around ’till here, I think you can manage the code at once:

	$(".container, .overlay")
	.animate({"opacity":"0"}, 200, linear, function(){
		$(".container, .overlay").remove();	

and for the css, add cursor:pointer; to the .overlay element to give people a visual clue that they can click it.

Pretty easy, no? You can actually define multiple elements in your jQuery selector. Just like in CSS, you can do so with just a simple comma.

The only gotcha here, is that you need to make sure this bit of code is within your lightbox function (see the full example below to see what I mean) otherwise it will not get executed.

Full code

To see the full code put together, check out the Demo page.

Remember, next week, we’ll expand on this a whole lot more, including some very cool stuff like nice animations and multiple lightboxes! See you then! :)

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!

  1. Monkeytail

    Sieht gut aus!


  2. Scott

    Nice work!
    One feature that I find missing from every lightbox script out there, is the ability to click the browser’s back button and have the page return to it’s previous state.
    If you could implement functionality like that, then it would put your lightbox script head and shoulders above the others.

  3. Thanks for this, definitely great starting information.

    Scott, check out this site about using JavaScript to master the backbutton. I’ve never personally used it, but it seems like it could be added to a lightbox implementation. (It is based on mootools, btw)

  4. Scott, this jquery plugin does history management, it doesn’t seem hard to integrate, but it does add another .js file.

  5. […] Building your own lightbox – Part 1 – Nützliches Tutorial. Diese Dinger tun ja nie ganz genau das, was man gerne hätte, […]

  6. […] Building your own lightbox – part 1 […]

  7. […] Building your own lightbox – part 1 […]

  8. adevv

    Thank you very much for sharing! This is very useful for me. Can’t wait for part 2 :)

  9. adevv

    Please write about how to display several images in lightbox using one thumbnail only (predefined image set). Thanks again.

  10. […] for the delay on the second part of Building your own lightbox. The article is proving itself to be, how do I say it, […]

  11. onlymed

    hello can we juste call lightbox from another javascript function means without a mouse click :

    when need show lightbox or hide it ? thanks a lot

  12. Great article! Keep up the good work. I look forward to Part 2! Adding to my feeds :)

  13. Hi. Nice tutorial but I really really needed a lot of the functions promised in part 2 about the lightbox showing other content besides images as well as the close buttons. Please can you mail me how to do this or create part two.

    Great work!

  14. asd

    Where the heck is part two???

  15. […] Building your own lightbox – part 1 Aucun des plugins type lightbox ne vous convient ? Alors essayer de faire le votre à l’aide de ce tutoriel ! […]

  16. […] Building your own lightbox – part 1 […]

  17. Thanks, very useful

  18. Thank you for the script! Works great on my images allthough I had to take away window from window.startOverlay() and window.removeOverlay().

  19. so simple in coded, i thinks this shorter coded in lightbox trick
    thanks :)

  20. Tom

    This is very helpful, and looks to provide the perfect base in which to create your own completely customised lightbox feature. Thank you!

  21. Nate

    1. Can you put videos in this lightbox?

    2. Can you join groups of images into “folders” by bracketing them like the original lightbox where it does something like this: class=”lightbox[group1]” and class=”lightbox[group2]” etc.?

    I’m really tired of having to tweak different lightboxes, so I appreciate this tutorial. Haven’t really had a good chance to study it closely, so I apologize if these issues were mentioned. I don’t think they were, though based on the terms I searched on this page.

  22. .. i just want to say Thank you .. very Useful

  23. Qwandale Coleman

    how can I add buttons to the overlay so as to pick another category with out leaving the overlay. For example: the overlay is up and initially its displays a pic belonging to a specific gallery category. I have the option to click a button that presents me with another gallery category, like videos perhaps.

  24. I completed it and it truly does work great.

  25. Leo

    “left: “50%”, —- is missing a [ ” ] after [ left ]

  26. Thanks for this, definitely great starting information.

  27. Better merchandise and also exelent outcomes for your folks who are seeking this lower price one on one mobile phone series here’s it TELEPHONE THESE DAYS 866-943-6381

  28. Thanks for this very Useful

  29. Louise

    Thanks for this, very useful and really well explained!
    Where can I find part 2?

  30. someguy

    WHERE IS PART 2 ? ! ? ! ? ! ? !

  31. Hi! Don’t you use Myspace? I’d prefer to follow you if that might be all right. I am absolutely enjoying your website and look forward to new blogposts.

  32. Simon

    I would suggest not to positioned the divs absolute but position them fixed. If you make the position absolute you fail if you have to scroll down to the lightbox link :)

  33. I make some changes for better function of LightBox:
    1: CSS: .overlay { position:fixed; …
    2: JS: $(“.container”).css({ “top”: $(window).scrollTop() + (document.documentElement.clientHeight / 2.0) + ‘px’, …
    $(“.container, .overlay”).animate({“opacity”:”0″}, 200, “linear”, function(){
    $(“.container, .overlay”).remove();

    Now it’s working with scrolling.

  34. Kelvin

    Pls i need help displaying multiple images in the Lightbox at the same time like so = ( ) if you browse to the Artist page , the link is located at the bottom of the Home page you could understand more of what i want to achieve. Thanks.

  35. I¡¦ve recently started a web site, the info you offer on this website has helped me tremendously. Thanks for all of your time & work.