Create a Lightbox with jQuery and CSS

The “lightbox” is a unique and useful design tool when used properly. It allows designers to present information that is totally independent from the site theme, and it is especially useful when displaying information that is loaded via AJAX requests (often negating the need for additional post-backs on your pages). There are countless ways to implement lightbox functionality into your site, and almost every option I’ve ever seen is weighed down by extraneous functionality or useless transition animations. It’s quite easy to create your own lightboxes with minimal effort. This tutorial can serve as a quick and easy template to get you started.

The CSS Style

There are two elements you’ll have to implement into your design in order to create a lightbox — CSS and Javascript. We’ll take care of the CSS style first, as it’s the most simple to implement. On your page or in an attached style sheet, add the following CSS styles:

#lightbox {
	position: absolute;
	top: 0;
	left: 50%;
	width: 500px;
	margin-left: -250px;
	background: #fff;
	z-index: 1001;
	display: none;
}
#lightbox-shadow {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: #000;
	filter: alpha(opacity=75);
	-moz-opacity: 0.75;
	-khtml-opacity: 0.75;
	opacity: 0.75;
	z-index: 1000;
	display: none;
}

What we just did: we established two styles. One style is for the lightbox that actually appears on the page (#lightbox). The second style is for lightbox background (#lightbox-shadow). We have made this background dark and semi-transparent in order to dim the site’s content as it appears behind the lightbox.

The jQuery Script

The real work is done via our simple jQuery script. We have two JavaScript functions that will handle displaying and hiding our lightbox. First, make sure you have attached the jQuery library to your page:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Now, in an attached .js file, add the following script code.

/****************************************
	Barebones Lightbox Template
	by Kyle Schaeffer
	kyleschaeffer.com
	* requires jQuery
****************************************/

// display the lightbox
function lightbox(insertContent, ajaxContentUrl){

	// add lightbox/shadow <div/>'s if not previously added
	if($('#lightbox').size() == 0){
		var theLightbox = $('<div id="lightbox"/>');
		var theShadow = $('<div id="lightbox-shadow"/>');
		$(theShadow).click(function(e){
			closeLightbox();
		});
		$('body').append(theShadow);
		$('body').append(theLightbox);
	}

	// remove any previously added content
	$('#lightbox').empty();

	// insert HTML content
	if(insertContent != null){
		$('#lightbox').append(insertContent);
	}

	// insert AJAX content
	if(ajaxContentUrl != null){
		// temporarily add a "Loading..." message in the lightbox
		$('#lightbox').append('<p class="loading">Loading...</p>');

		// request AJAX content
		$.ajax({
			type: 'GET',
			url: ajaxContentUrl,
			success:function(data){
				// remove "Loading..." message and append AJAX content
				$('#lightbox').empty();
				$('#lightbox').append(data);
			},
			error:function(){
				alert('AJAX Failure!');
			}
		});
	}

	// move the lightbox to the current window top + 100px
	$('#lightbox').css('top', $(window).scrollTop() + 100 + 'px');

	// display the lightbox
	$('#lightbox').show();
	$('#lightbox-shadow').show();

}

// close the lightbox
function closeLightbox(){

	// hide lightbox and shadow <div/>'s
	$('#lightbox').hide();
	$('#lightbox-shadow').hide();

	// remove contents of lightbox in case a video or other content is actively playing
	$('#lightbox').empty();
}

Ready for Lightboxing

Once you have the CSS and script into place, you can call your new lightbox(); function from anywhere within your design. It’s as easy as calling the lightbox from an anchor tag:

<a href="javascript:lightbox('Hello!');">Show me the lightbox</a>

Remember, clicking anywhere on the “shadow” <div/> will hide the lightbox — you could easily add a “close” button to your lightbox by connecting it to the closeLightbox(); JavaScript function.

Similarly, you can insert HTML (or even a jQuery DOM object) into the lightbox. Like so:

<a href="javascript:lightbox('<p><strong>Rich</strong> content works too!</p>');">Show me the lightbox</a>

Finally, you can even use this simple lightbox function to insert AJAX content. Please keep in mind that my JavaScript function simply inserts the entire result into the #lightbox element — if you’re trying to request a website or HTML page, you’ll probably have to remove the <html/> and <body/> tags before inserting content into your lightbox window, else the lightbox would simply disappear. An AJAX lightbox request looks a little like this:

<a href="javascript:lightbox(null, 'https://foo.com/readme.txt');">Show me the lightbox</a>

The Demo

If you’re on a fast connection, you may not notice, but the AJAX link actually reads “Loading…” in the lightbox a split-second before the content actually appears. This can be useful to give users feedback while the AJAX request is processing. Please note that I’ve added a bit of styling to my demo (namely padding on the lightbox to make it appear less cluttered).

Make it Shine

You’ll probably want to modify the CSS and other elements of this lightbox in order to suit your site’s design and style. If you’re working with a lot of AJAX content, you may want to even replace the temporary loading element with an animated spinner image, or something of the like.

To help you get started, you can download the CSS and JavaScript referenced in this tutorial here:

Good luck, and happy styling!

63 comments

  1. Kyle says:

    Rich, thanks for the suggestion! I’ve added a demo to the tutorial (above).

  2. Père says:

    Not the usual revelation this time.

  3. Bruce says:

    I have not really dug into web design and development for quite some time. I just started up my site again (not linking it because its still barren) and this is quite enlightening. Thanks!

  4. marisa says:

    My images are inside div’s as background. How can I apply the light box effect?

  5. Brandon says:

    Marisa – you can use javascript to accomplish this. Put onclick=”lightbox(‘insert content’);” within your div and it should work.

  6. Roy says:

    Hello,
    For some reason the ‘height: 100%’ doesn’t work for me.
    It only fills up a browser sized overlay.
    But if you scroll downards it ends on te bottom of my monitor.
    Do you have any idea how i could fix this?

    Thanks
    ~Roy~

    • Kyle says:

      Roy, you might try changing position: absolute on the shadow DIV to position: fixed. Depending on your design, this could possibly clear it up for you.

      • Roy says:

        Thank you.
        That fixed it!

        ~Roy~

      • bruno says:

        another solution would be to add this line right before the “display lightbox” lines (before lines 54-55):

        // make shadow same height as document
        $(‘#lightbox-shadow’).css(‘height’, $(document).height()+’px’);

        This will get the document’s height and adjust the shadow to fill it

  7. Roy says:

    I cannot use a link within the content of that lightbox right?
    <a href="javascript:lightbox('Click here‘); ” style=”text-decoration: none;”>

    Thanks
    ~Roy~

    • Roy says:

      Not sure how to show you, since this page automaticly converts the link code within into a real link.

      • Kyle says:

        Regular links (<a>) should work just fine; do you want to open another lightbox from within a lightbox? If that’s the case, you might have to modify the script to allow for two boxes.

        • Roy says:

          Alright one more thing….
          I also wanted to add a click action on a div within a lightbox.
          I added this to the jQuery:

          $(‘div#no’).click(function () {
          closeLightbox();
          });

          Its not working, can you help me out?

          Thanks
          ~Roy~

          • Roy says:

            Nevermind, after a long search I solved the problem.

            $(‘div#no’).live(‘click’, function() {
            closeLightbox();
            });

  8. Mark says:

    Because the shadow did not span throughout the entire height when I scroll I changed it to fixed as you suggested
    This works, however, scolling then becomes slow.
    Why does position absolute not work always?

  9. habeebperwad says:

    Will it work in all browsers especially IE6?

    • Kyle says:

      Not really sure – lately I’ve only ventured into IE6 for cursory testing (to make sure everything is readable) or if a client pays me exorbitant amounts of money to do so! It’s largely not a “supported” browser in most companies, especially in the US, where it now commands less than 2% of the browser market. Let me know what you find.

  10. Niixie says:

    I have a problem, because, i dont know how to use divs inside the lightbox, if i do it changes the link?

    Is there any way i can use divs inside it?

    • Kyle says:

      Niixie, divs will work just fine. Use the second example under “Ready for Lightboxing” in my tutorial – just swap out my string of HTML for your own HTML (divs included).

  11. Jeff Potter says:

    I, too, had trouble with links but solved it by using " instead of escaping double quotes for the URL.

  12. Jeff Potter says:

    (I actually typed in the ampersand-quot-semicolon entity in the last comment, but it displayed, as one should expect, as the actual ” glyph.)

  13. Jon says:

    Hi,

    I love this tutorial. It’s the most versatile lightbox I’ve found.

    Thanks a lot!

  14. Tim says:

    I receive a ‘staff_lightbox is undefined error. I renamed it staff_lightbox since I have an existing ‘lightbox’ script from lightbox.org and didn’t wanted to risk having a conflict of variable names

  15. pawan says:

    thanks for this code , this is very useful for me ……………………….thx again

  16. Shir Gans says:

    Hi,
    Thank, this is great tutorial.
    got some suggestions to make it a bit more fluid:

    Auto Width & Center
    Instead of having the width in the CSS, make it width: auto; and on you .js file, find the following line:

    $('#lightbox').css('top', $(window).scrollTop() + 100 + 'px');

    And add beneath it:

    $('#lightbox').css('marginLeft', '-' + $('#lightbox').width() / 2 + 'px');

    Fade-in & Fade-out
    find the following line of code in your .js file:

    $('#lightbox-shadow').show();
    $('#lightbox').show();

    And replace it with:

    $('#lightbox-shadow').fadeIn('fast', function(){
    $('#lightbox').fadeIn('fast');
    });

    After that, replace the following line:

    $('#lightbox-shadow').hide();

    With this one:

    $('#lightbox-shadow').fadeOut('slow');

    Cheers !

    • jen says:

      Thanks for the fade in and out… works perfectly!! Any chance you know how to make it an image in the shadow box instead of text?? – Many thanks!!

  17. Alex says:

    Thanks for the article, was very helpful and clear.

  18. yashcoder says:

    Dude thanks! its a very simplified explaination 😀

  19. Kyle says:

    This is really cool! How could I use it to show photos, and have them transition?

    • Kyle says:

      Kyle, transitioning between photos requires a bit more scripting to make it work. Basically, you have to load the image in JavaScript, and get the size of the image before you can figure out how to animate the size of the lightbox. Check out my portfolio (“My Work”) and “view source” to see how I did it there, if you’re interested.

    • Navin says:

      Hi Peter, thanks for your kind word. Since you are new I would like to say, we all proreammgr work like this, we share our code and help each other. I will wait for a day when I use your shared code. About the problem you suggest, well I never had that problem with my inital code, I never give height to my Ima tag or video tag, what I basically do is I send thumbnail of the size that I need in popup box I show full image. It maybe your code is confusing with other included JS. Maybe you should try to to use without other code on same page.

  20. Alan says:

    After some trial and error I was able to get the lightbox working, but I can’t seem to connect the closeLightbox function to the lightbox-close DIV the way that you did on your portfolio page. Any help would be greatly appreciated!

    • Alan says:

      I was able to get the closeLightbox function to work…but now I’m struggling with another challenge. I want to use the lightbox on the same site for 2 different applications, which are very different sizes. I changed the height and width of the lightbox div to auto, which is working great…but I can’t seem to get it to automatically center on the page. I would like it to appear in the center whether I’m displaying my 480px Login window, or my 720px Sign-Up screen.

      Sorry if this is a basic question – I’m pretty new to this!

  21. Ramon says:

    Hi its working great!, but the problem is i need to put some PHP inside, and then it crash 🙁 how can i solve this.

    thanks!

  22. Laetitia says:

    I am using this script, however, I updated the jquery src to the latest, 1.7.1 (as of today). Whenever I try to load any external content into the lightbox I get the AJAX failure pop-up. Any thoughts? Help would be greatly appreciated…

    • Martin says:

      Laetitia, had the same problem. I searched on jquery.com and found that: Due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
      So, your data have to be on the same server.

  23. oil.ali says:

    Hello,

    it’s really a great example, and its works perfectly if I use it with text only, but if I like to show my image in the lightbox, the javascript opens the file – not the image, just the file content.

    It’s possible to show my images only, or I must generate a html with an image tag for any of image files? (no, please…)

    Thank you for the answer.

  24. rockey says:

    I had created a page in that i had used this lightbox and now i want to add a close button on top of box

    Plz help me out to solve my problem

  25. steve says:

    I would love to know how to substitute a picture in the lightbox call up instead of type! I’ve tried a few things but no success it only disables it. I’m new to all this so please take it easy on me 🙂

  26. Alex says:

    Hi I’m in the same boat as Steve! Also would love to know if video i.e youtube link is supported by this too? Many Thanks

  27. Jafor Iqbal says:

    It’s really nice post and i am use it, in my client site, it’s works for me, thank you brother, this is a big help for me

  28. Arunagiri says:

    It is not working with a message contains single quotes.

  29. santosh says:

    very good.

  30. jen says:

    Hello this is super cool! Any chance we can see how to put an image instead of text in the shadow box??
    I have tried several things and nothing seems to work.??

    Many Thanks

  31. Anonymous says:

    Thanx….Nice Tutorial..very very Thanx

  32. Mark Z says:

    Thank you very much indeed – this worked great for me.

  33. James says:

    Kudos to you. This was a great little tutorial.

  34. Sara Tenenbaum says:

    Kyle-
    As always you come thru for me. I really appreciate it.

    Sara

  35. Martijn van Tol says:

    Nice script, but how can I make the lightbox go over Iframes? I’m calling the function in a page that is in a frame and the lightbox stays also in that frame. I want the lightbox to “hover” over the complete page. Any suggestions?

  36. Katia says:

    Hi,

    It’s a really nice tutorial.
    I’m wondering is there a way to make it appear bigger on mobile phone?
    I’m using it for displaying text and the text seems so small on mobile device.

    Thanks

  37. Sam says:

    Hi,

    How do i go about implementing this on SharePoint 2013. kindly assist