Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 3

Drew Griffith
Drew Griffith
3,926 Points

Overlay Appearing On Load

I'm trying to figure this out, i've looked back at the html, css, and jquery a few times compared to the video however when I preview the code the overlay already exists on load without an image, ignoring the click.

//Problem:User when clicking on image goes to a dead end
//Solution: create an overlay with the large image - Lightbox

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");

$overlay.append($image);
// Add overlay
$("body").append($overlay);
  //An image
  //A caption


//1. Capture the click event on a link to an image
$("#imageGallery a").click(function(event){  
  event.preventDefault();
  var imageLocation = $(this).attr("href");

  //Update overlay with the image linked in the link

  $image.attr("src", imageLocation);
  //Show the overlay.
  $overlay.show();

  //Get child's alt attribute and set caption

  });

//When overlay is clicked
  //Hide the overlay

2 Answers

In the video, Andrew uses the CSS rule display:none; to initially hide the overlay from showing.

Drew Griffith
Drew Griffith
3,926 Points

Thank you Jason Massey, I missed that completely.

Andrew Shook
Andrew Shook
31,709 Points

I'm not sure how Andrew Chalkley did it in the course, but you can add this to your CSS file:

#overlay{
   display:none;
}

or you could add this to your jQuery file:

$("body").append($overlay);
//hide overlay
$overlay.hide();

CSS would be better since it will hide to overlay even it JavaScript encounter an error.