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

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

The append() method called on the body does't work until its called within the click() method. What gives?

Code in video...

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

$overlay.append($image);

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

$("#imageGallery a").click(function(event){
  event.preventDefault();
  var imageLocation = $(this).attr("href");

  $image.attr("src", imageLocation);

  $overlay.show();
});

The above code doesn't work until I move $("body").append($overlay);

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

$overlay.append($image);


$("#imageGallery a").click(function(event){
  $("body").append($overlay);
  event.preventDefault();
  var imageLocation = $(this).attr("href");

  $image.attr("src", imageLocation);

  $overlay.show();
});
Mark VonGyer
Mark VonGyer
21,239 Points

have you tried the javascript console to see what is happening?

You could put a console.log message after the first attempt to see if it is processed.

Also check for errors on console.

The div is appended to the body before the <a> tags are clicked, therefore displaying the dark transparent background from the beginning. There aren't any errors in the javascript console. I'm not too familiar with jQuery, what would I be console logging?

Mark VonGyer
Mark VonGyer
21,239 Points

I have a sneaky suspicion it is to do with the $overlay.show() line

2 Answers

Ebrahim Haji
Ebrahim Haji
6,712 Points

Just fork your workspace

I had the same problem. It turns out I forgot to add : display:none; in the #overlay selector in the style.css file.