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 2

My code won't work

My code won't work.. I tripled check appending the overlay as well as did everything that the teacher asked. Code still won't work.

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

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

// An image to overlay
$overlay.append($image);

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

 // A caption
$overlay.append($caption);

// Capture the click event on a link to an image
$("a #imageGallery").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
  var captionText = $(this).children("img").attr("alt");
  $caption.text(captionText);
});


// When overlay is clicked
$overlay.click(function(){
 // Hide the overlay
  $overlay.hide();
});

updated code formatting

2 Answers

Michal Weizman
Michal Weizman
14,050 Points

Hi Melvin, I think you got the order of 2 tags mixed up. You need to target all of the "a" tags insids the tags with the id="imageGallery", like so:

$("#imageGallery a")

However, your code says:

$("a #imageGallery")

I hope this helps...

Tobias Helmrich
Tobias Helmrich
31,602 Points

Hey there Melvin,

at first I thought the problem exists because you're not selecting any elements in your variables but I think that this might be because of formatting issues in the forums. Please make sure to format your code properly so it's easier to find the problem! :)