jQuery Lightbox: A Pop-up Image Viewer

Free JavaScript & jQuery Tutorial

Discover how to enhance user experience on your website by learning how to use JavaScript & jQuery to create a lightbox effect for your photos.

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Grouping the photos into a gallery, Adding captions, Removing the counter, Customizing the appearance

Exercise Preview

jquery lightbox example

Exercise Overview

When a user clicks a thumbnail image to see a larger version, there are numerous ways to handle what happens next. The thumbnail could link to another page, but then a user must click the Back button to return to the page. While pop-up windows can work, their appeal has been tarnished by pop-up ads and they don’t work well on tablets or mobile devices.

Another option is to use JavaScript to create a “lightbox” effect. The images open within the page (over the page’s content), and are user-friendly. Users can easily switch between photos with buttons or keystrokes, and close it with a button or keystroke! In this exercise, you’ll learn how to use a free jQuery lightbox plugin called Magnific Popup.

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Getting Started

  1. Open your code editor if it isn’t already open.

  2. Close any files you may have open.

  3. For this exercise we’ll be working with the Lightbox-Gallery folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. You may want to open that folder in your code editor if it allows you to (like Visual Studio Code does).

  4. Open photo-gallery.html from the Lightbox-Gallery folder.

  5. Preview photo-gallery.html in Chrome (we’ll be using its DevTools later).

  6. Click some of the photos in the gallery to see that they currently are just normal links that take you to enlarged pictures. Let’s spruce things up.

  7. Leave the page open in Chrome so we can come back to it later.

Linking to the Plugin Files

We’ve included the Magnific Popup file in our class files, but you can also visit dimsemenov.com/plugins/magnific-popup to download it, read the documentation, and see examples.

At a minimum, Magnific Popup requires three files to run—jQuery, the Magnific Popup JS file, and the Magnific Popup CSS file. This page already has jQuery linked, so we just need to add the Magnific Popup files. Let’s link to the CSS file first.

  1. Return to photo-gallery.html in your code editor.

  2. It’s important to link to the Magnific Popup CSS before our custom CSS. This way our CSS code will override any styling in the plugin. Above the link to main.css around line 6, link to the Magnific Popup CSS file as shown in bold:

       <title>The Jive Factory</title>
       <link rel="stylesheet" href="js/vendor/magnific/magnific-popup.css">
       <link rel="stylesheet" href="css/main.css">
    </head>
    
  3. Next we’ll link to the Magnific Popup JS file. Around line 109, after the jQuery link, add the following code:

    <script src="js/vendor/jquery-2.1.0.min.js"></script>
    <script src="js/vendor/magnific/jquery.magnific-popup.min.js"></script>
    <script src="js/main.js"></script> 
    
  4. Save the file.

Initializing the Pop-up

  1. We’ve linked to all the files, so we’re ready to initialize Magnific Popup. We’ll start with a prepared code snippet we got from the documentation on the Magnific Popup website. From the snippets folder, open magnific-example.js.

  2. This code initializes the magnificPopup() function. When you click any link (the a tag), it will load an image into the pop-up. Select and copy all the code.

  3. From the js folder, open main.js.

  4. Put your cursor on the empty line 34 below the // Lightbox comment and paste the code as shown in bold:

       // Lightbox
       $('a').magnificPopup({
          type: 'image'
       });
    
    });
    
  5. Save main.js.

  6. Switch to Chrome and reload photo-gallery.html.

  7. Click on any of the 12 thumbnails in the photo gallery to test out the lightbox. A larger photo should appear and the rest of the page will darken. Close the pop-up by clicking the X at the top right of the image, or by clicking outside the photo.

  8. Click on The Jive Factory logo on the top left of the page. This should display an error that the image can’t be loaded. That’s because that image links to index.html and not an image. We shouldn’t be targeting all links, just the links in the gallery.

  9. Switch back to main.js in your code editor.

  10. All the thumbnail images reside in a div which has the ID of gallery. Around line 34, change the code to target only the links inside the gallery div:

    $('#gallery a').magnificPopup({
       type: 'image'
    });
    
  11. Save main.js.

  12. Switch to Chrome and reload photo-gallery.html.

  13. Click the image thumbnails and logo again. Notice that only the links to photos in the gallery get the pop-up effect. Sweet!

Grouping the Photos into a Gallery

It would be nice if the photos were grouped together so that the user could go between them with next and previous buttons (or keystrokes). Magnific Popup makes this very easy!

  1. Switch back to main.js in your code editor.

  2. Add the following bold code:

    $('#gallery a').magnificPopup({
       gallery: {
          enabled: true
       },
       type: 'image'
    });
    
  3. Save main.js.

  4. Switch to Chrome and reload photo-gallery.html.

  5. Click on any photo thumbnail to see the pop-up.

  6. There should now be arrows on the left and right sides of the page. Click them to change images.

  7. Press the Left or Right Arrow key on the keyboard. Nice! Users can navigate through the images with the Arrow keys or by clicking the buttons.

  8. There’s one more way to change photos. Click on the enlarged photo to advance to the next image.

  9. Close the enlarged image using any of the following methods:
    • Click the X at the photo’s top right corner.
    • Press the Escape (Esc) key.
    • Click anywhere on the page outside the enlarged image.

Adding Captions

Magnific Popup can add captions to the enlarged images. To do this it looks at the title attribute of the link that is clicked. If the link has a title, it will add it as a caption. If there is no title, then there’s no caption. None of our links currently have titles, so let’s add some.

  1. Switch back to your code editor.

  2. Switch to photo-gallery.html so we can add some markup.

  3. Find the code for the #gallery div around line 68.

  4. On the first link, add the bold title attribute as shown below:

    <div id="gallery">
       <a href="img/gallery/bugs1.jpg" title="Working Double-Time"><img src="img/gallery/thumbs/t-bugs1.jpg"></a>
    
  5. Save the file.

  6. Switch to Chrome and reload photo-gallery.html.

  7. Click on the top left thumbnail image. Below the enlarged image, you should see the title Working Double-Time.

  8. Let’s do another one. Back in your code editor, for the second link, add the bold code as shown below:

    <div id="gallery">
       <a href="img/gallery/bugs1.jpg" title="Working Double-Time"><img src="img/gallery/thumbs/t-bugs1.jpg"></a>
       <a href="img/gallery/bugs2.jpg" title="Melodica Solo"><img src="img/gallery/thumbs/t-bugs2.jpg"></a>
    
  9. Save the file.

  10. Switch to Chrome, reload photo-gallery.html, and:
    • Again click the top left thumbnail image and notice the caption below the enlarged image.
    • Press the Right Arrow key and notice the caption changes for the next photo.
    • Press the Right Arrow key again and notice the caption disappears, because this photo doesn’t have a title.
    • While we’re looking below the image, notice on the bottom right there is an image counter. It’s fine if you want it, but let’s see how to remove it if you don’t.

    NOTE: We could add titles (captions) to the rest of the images, but we think you get the idea, so we’ll just move on.

Removing the Counter

  1. Switch back to your code editor.

  2. Switch to main.js.

  3. To remove the counter, we need to customize its text option. By setting the text to nothing, we’ll remove it! Add the following bold code, but don’t miss the comma at the end of the enabled line above it!

    $('#gallery a').magnificPopup({
       gallery: {
          enabled: true,
          tCounter: '' // those are two single quotes!
       },
       type: 'image'
    });
    

    NOTE: Options end with a comma if they are followed by another option. The last option has no end comma. Forgetting this can break the whole thing!

  4. Save main.js.

  5. Switch to Chrome and reload photo-gallery.html.

  6. Click on the top left thumbnail image. The counter should not be there anymore. Keep the lightbox open, we’re not done with it yet.

Customizing the Look of the Captions

We can change the styling of the captions with CSS. First we need to find out how Magnific Popup is styling them.

  1. The caption should be visible on the bottom left of the enlarged image. Ctrl–click (Mac) or Right–click (Windows) on the caption text and choose Inspect.

  2. In the DevTools you should be able to see that the caption is wrapped by <div class="mfp-title"> which we can target for styling!

  3. While we’re in the DevTools, make sure the .mfp-title div is selected, and on the right side notice the CSS. You should see it has padding-right: 36px; (to make room for the counter). We want to center the text, so now that we’ve removed the counter, we must also remove this padding or the text won’t be properly centered.

  4. Switch back to your code editor.

  5. From the css folder, open main.css.

  6. Below the #contentPanel #gallery a style around line 99, add the following:

    .mfp-title {
       padding-right: 0;
       text-align: center;
       color: #f6cf70;
       font-weight: bold;
       text-transform: uppercase;
       font-size: 14px;
    }
    
  7. Save main.css.

  8. Switch back to Chrome and reload photo-gallery.html.

  9. Click the top left thumbnail image to see that the caption should now be centered, a new color, uppercase, and slightly larger than before. Keep the lightbox window open, we’re not done with it yet.

Customizing the Overlay’s Background Color

Magnific Popup adds an overlay behind the enlarged photo to help separate it from the page’s content. We can change the color of that, and we’d like to lighten it.

  1. With the lightbox still open, Ctrl–click (Mac) or Right–click (Windows) outside the enlarged image (on the background) and choose Inspect.

  2. In the DevTools, find the first tag inside the body tag. It should be <div class="mfp-bg mfp-ready"></div>.

  3. Select that tag and on the right, find the .mfp-bg rule.

  4. Notice it has a background of #0b0b0b.

  5. Switch back to main.css in your code editor.

  6. Below the .mfp-title style (which starts around line 105) add the following:

    .mfp-bg {
       background: #333;
    }
    
  7. Save main.css.

  8. Switch back to Chrome and reload photo-gallery.html.

  9. Click on any thumbnail image and notice the background is now a bit lighter. Keep the lightbox window open, we’re not done with it yet.

Customizing the Look of the Arrows

  1. While you still have the lightbox open, notice the arrows have a faint outline around them. It’s very close in color to the background, so you may not be able to see it depending on the brightness and contrast of your monitor. Don’t worry if you can’t see it, but know that we can change the fill or outline color of the arrows. Let’s do that next!

  2. Ctrl–click (Mac) or Right–click (Windows) on the lightbox’s right arrow (next) and choose Inspect.

  3. In the DevTools, expand the button element to see the ::before and ::after elements inside.

    inspect lightbox next arrow

    NOTE: The ::before element is the outline and the ::after element is the fill.

  4. Select the ::before element.

  5. In the Styles on the right, find the .mfp-arrow-right:before rule and notice that it has a property declaration of: border-left: 27px solid #3f3f3f;

  6. Select the ::after element.

  7. In the Styles on the right, find the .mfp-arrow-right:after rule and notice that it has the following property declaration: border-left: 17px solid white;.

    To adjust the color of the fill and outline we can change these two elements. If we made you manually style these, you’d do a bunch of copying and pasting class names, colors, etc. so we’ve saved you some time and made a snippet.

  8. Switch back to your code editor.

  9. From the snippets folder, open magnific-arrow-colors.css.

  10. Select and copy all the code.

  11. Switch back to main.css.

  12. Paste the new rules below the .mfp-bg rule (which starts around line 113).

    NOTE: You can use this snippet in your own projects, but you’ll want to customize the colors to fit your design.

  13. Save main.css.

  14. Switch to Chrome and reload photo-gallery.html.

  15. Click on any thumbnail image and notice the arrow colors better fit our design. Hover over them and notice the opacity changes so they appear brighter.

  16. All that’s left to do is customize the color of the close X button at the top right. Ctrl–click (Mac) or Right–click (Windows) on it and choose Inspect.

  17. In the DevTools you should see a button element with a class of mfp-close. That’s what we can target with CSS.

Customizing the Look of the X Close Button

  1. Switch back to main.css in your code editor.

  2. Below the .mfp-bg style (which starts around line 113) add the following:

    .mfp-close {
       color: #f6cf70;
    }
    
  3. Save the file.

  4. Switch back to Chrome and reload photo-gallery.html.

  5. Click on any thumbnail image and notice the close X is still white, instead of the yellow we want. Why didn’t our style work?

  6. Ctrl–click (Mac) or Right–click (Windows) on the close X button and choose Inspect.

  7. With the mfp-close button selected in the code, look in the Styles on the right. The name of the rule with the color: white property declaration is .mfp-image-holder .mfp-close.

    By specifying the extra container’s class, their rule is more specific than ours and overrides our CSS. Luckily that’s easy to fix.

  8. Switch back to your code editor.

  9. Around line 116, add another selector to the .mfp-close rule as shown in bold below:

    .mfp-image-holder .mfp-close {
       color: #f6cf70;
    }
    
  10. Save the file.

  11. Switch to Chrome and reload photo-gallery.html.

  12. Click on any thumbnail image and notice the close X is now yellow. Lookin’ good!

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Lightbox-Gallery.

fancyBox: Another Good Lightbox

There are tons of jQuery lightboxes. All of them work pretty similarly, but we’re not thrilled by all of them. Some aren’t attractive, or have slow animations that are annoying as a user. One lightbox we particularly like is fancyBox. You can learn more at fancyapps.com and try it out for free. It’s free for personal use and non-profit websites. For commercial use you can purchase a license for one website or for unlimited websites.

While Magnific loads faster, two things that set fancyBox apart is how it animates the lightbox. It can animate open and closed. Magnific’s Zoom option doesn’t animate things open unless they are preloaded (which they aren’t until you’ve opened them). Secondly, fancyBox has a thumbnail option not found in Magnific. It’s a nice alternative. Both are great, so use whichever suits your needs best.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram