Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

This chapter is from the book

Creating a Lightbox Effect

In the next few exercises you’ll use several of the DOM manipulators to create a lightbox effect. Many websites use a lightbox effect to show enlargements of photographs centered and highlighted on web pages. You’ll be able to use the effect on your web pages too, once you’ve learned how to put together the function.

Some of the manipulators that you’ll use during the exercise are specifically designed for getting or modifying information about CSS. These are described in Table 4.2.

Table 4.2. DOM CSS Manipulators


Use It To...


Get or set the value of a style property for the first element in the set of selected elements.


Get the current computed height for the first element in the set of selected elements.


Get the current computed height for the first element in the set of selected elements, including the padding but not the border.


Get the current computed height for the first element in the set of selected elements, including padding, border, and optionally, margin.


Get the current computed width for the first element in the set of selected elements.


Get the current computed width for the first element in the set of selected elements, including the padding but not the border.


Get the current computed width for the first element in the set of selected elements, including padding and border.


Get the current coordinates of the first element in the set of selected elements, relative to the document.


Get the current coordinates of the first element in the set of selected elements, relative to its parent element.


Get the current number of pixels hidden from view to the left of any scrollable area for the first element in the set of selected elements.


Get the number of pixels hidden above any scrollable area for the first element in the set of matched elements.


Remove the set of selected elements from the DOM.


Remove an attribute from each of the selected elements.


Replace each target element with the set of selected elements.


Replace each element in the set of selected elements with new content.


Wrap an HTML structure around each element in the set of selected elements.


Remove the parents of the set of selected elements from the DOM.


Wrap an HTML structure around all elements in the set of selected elements.


Wrap an HTML structure around the content of each element in the set of selected elements.

The first order of business is covering the current page with a translucent background on which the photograph will be displayed.

To use the append() method to display a translucent shade

  1. Open gallery.html in your text editor and add the data-photo attribute to each of the list items (Script 4.1.html):
    <img src="images/thumb_lv01.jpg" data-photo="images/lv01.jpg" alt="Classic Sign - Las Vegas" />
    <img src="images/thumb_lv02.jpg" data-photo="images/lv02.jpg" alt="New York New York - Las Vegas" />
    <img src="images/thumb_lv03.jpg" data-photo="images/lv03.jpg" alt="Neon Lights - Las Vegas" />
    <img src="images/thumb_lv04.jpg" data-photo="images/lv04.jpg" alt="Stratosphere -  Las Vegas" />
    <img src="images/thumb_lv05.jpg" data-photo="images/lv05.jpg" alt="Wynn Hotel - Las Vegas" />
    <img src="images/thumb_lv06.jpg" data-photo="images/lv06.jpg" alt="Paris - Las Vegas" />
  2. Save the gallery.html file and upload it to your web server.
  3. Edit jquery.custom.js and insert the following code to add a translucent background to the browser window:
    $('.imageGallery li img')
    .click(function() {
    ('<div class="shade"></div>');
    .css('opacity', 0.7).fadeIn();
  4. Save the jQuery file and upload it to your server.
  5. Click on any of the images in the photo gallery and the background should appear. There’s no way to get rid of it at this point without reloading the page. You’ll add code to remove it later red-a.jpg.

    Click to view larger image

    red-a.jpg The backdrop is in place for the lightbox.

For the backdrop to appear, you have to append a div to the body element of your page and declare the shade class on the div (the shade class is already defined for you in css/base.css). At this point, you apply a CSS opacity property (to make the backdrop translucent) and use fadeIn() to bring the backdrop into view. (More on fadeIn() and other effects in Chapter 8, “Creating Captivating Effects.”)

Take a look at your DOM inspection tool while you have the div applied to the body. Notice that the backdrop div is the last element within the body tags because append() inserts content at the end of the selected element red-b.jpg.


Click to view larger image

red-b.jpg The backdrop div element is the last element within the body tags.

With the backdrop in place, it’s time to add the photo. There will be two things you’ll have to take care of: preloading all the full-sized images and placing the image centered on the browser window.

The reason for preloading the images is to ensure that the lightbox function can properly measure the image and know how to place it within the window. The jQuery methods can’t get the height and width of an element that isn’t currently available in the DOM. Failing to perform this step results in the image not being centered properly red-c.jpg.


Click to view larger image

red-c.jpg The top-left corner of the image is centered on the screen rather than the whole photo.

You’ll also use the browser window’s height to set the size of the image to make sure the photo is fully displayed within the boundaries of the browser window. Many of the full-sized images in the example are either taller or wider than the browser window red-d.jpg.


Click to view larger image

red-d.jpg You can never tell how tall the Statue of Liberty is until you try to fit her in a browser window.

As a matter of organization, most developers will group functions like the image preloader near the top of their jQuery file. In this case, the preloader needs to have completed its job before the lightbox function is called, so let’s put the preloading function together first.

To create an image preloader using appendTo()

  1. Edit your jQuery file to add the image preloader:
    function preload(arrayOfImages) {
    $('<img />')

    You start by declaring a function named preload. The function is given the argument of arrayOfImages. Once the function is called, the jQuery method each() loops through each item in the array that you’ll pass to the function. (More on each() in Chapter 9, “Turning on jQuery’s Utilities.”)

    For each image, you append an image tag to the body. Then you set the src attribute for the image tag to the current image information. Finally, you make sure the images are not visible until you need them by setting their CSS display method to none.

    Using appendTo() here makes perfect sense because it allows you to specify attributes more easily for each image tag prior to the tag being added to the page.

  2. Create the array inside a function call to preload:

    The square brackets indicate a JavaScript array using JavaScript Object Notation. The path for each full-sized image has been specified in a comma-separated list. Have a look at your DOM inspector and you should see the image tags just before the closing body tag red-e.jpg.


    Click to view larger image

    red-e.jpg The new image tags have been appended to the body.

Now let’s add further to the lightbox function.

To use height() and width() to set an element’s size and position

  1. Open jquery.custom.js in your text editor.
  2. Add the following jQuery code to create an image tag:
    var imgSRC = $(this).attr('data-photo');
    var imgTAG = '<img src="'+ imgSRC + '" />';

    This code should be added immediately after the line where you applied fadeIn() to the backdrop.

  3. Continue the function by adding the following code to append the modal window to the body and the image tag to the modal window:
    .append('<div class="photoModal">
    <a href="#" class="closePhoto">
    Close X</a></div>');

    The additional append() method adds an anchor tag to the modal, which will be used for closing the photo.

  4. Enter the code to check the window’s height and apply the height to the image:
    var windowHeight = $(window).height();
    $('.photoModal img')
        (windowHeight - 200));

    You’ve subtracted 200 pixels from the window’s height to ensure that the image will fit in the browser window.

  5. Save information about the modal’s current height and width to two variables. These two variables will be applied to the modal to center it horizontally and vertically within the browser window:
    var modalTopMargin = ($('.photoModal')
        .height() + 20) / 2;
    var modalLeftMargin = ($('.photoModal')
        .width() + 20) / 2;

    The reason you add 20 to the height and width is because the CSS specified for the modal window has a border of 10 pixels per side red-f.jpg.


    Click to view larger image

    red-f.jpg Take note of the border to make sure the photo is perfectly centered.

  6. Add the code to apply the CSS to the modal:
    .css({'margin-top' : -modalTopMargin, 'margin-left': -modalLeftMargin});

    In the original CSS (see css/base.css) for the modal, the top-left corner is originally set to be in the center of the screen. The top-left corner of the browser window is at coordinates 0, 0 red-g.jpg.


    Click to view larger image

    red-g.jpg The base coordinates for the browser window start at the upper-left corner.

    To make sure the photo is centered, you apply negative measurements from the photo’s top-left corner to move it into position red-h.jpg.


    Click to view larger image

    red-h.jpg By calculating the photo’s height and width, you can apply negative numbers to move it into position.

  7. Save the jQuery file and upload it to your web server. Reload gallery.html into your web page and click on one of the pictures red-i.jpg.

    Click to view larger image

    red-i.jpg The picture is sized and presented!

There’s only one problem at this point: you can’t close a picture once you’ve opened it. Because you’ve added elements to the DOM that were not previously there, you’ll have to use a special way to attach event handlers to account for the new elements.

To close the picture using remove()

  1. Reload jquery.custom.js into your text editor.
  2. Add the following function to the file:
    .on('click', '.closePhoto', function(e){
    $('.photoModal, .shade')

    The on() method accounts for elements either in the DOM now or added in the future. You use it to bind event handlers to items within a selected element. In the exercise, you attached the click event handler to the body and specified that the handler should answer to any item having the closePhoto class. You’ll recall that you appended an anchor tag having the class closePhoto in the previous exercise.

    Once the tag is clicked, the photo modal and the backdrop are faded and then removed using the remove() method, allowing the lightbox function to be reset for its next performance.

    You have undoubtedly noticed the preventDefault() method used here. You passed the click event e to the function:


    To keep the link from acting normally, which is typically navigating to another page, you applied the preventDefault() method to the event, which does what it says—it prevents the default event action from occurring.

  3. Save the file and upload it to your web server.
  4. Reload the gallery.html page. Click on an image and then click on the “Close X” link at the bottom right of the image. Your gallery page has returned to normal.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020