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

Mark Brady
Mark Brady
6,239 Points

What is this for: // Update overlay with the link clicked in the link $img.attr("src", imgLocation);

Everything else seems to make sense, but this line of code doesn't make sense to me. Can anyone help me understand? Thank you!

// Problem: User when clicks an img goes to a dead end
// Solution: Create an overlay with the large img - lightbox

var $overlay = $('<div id="overlay"></div>');
var $img = $('<img>');
$overlay.append($img);
// Add overlay 
$('body').append($overlay);
  // An img
  // A caption

// Capture the click event on a link to the img
$('#img-gallery a').click(function(event){
  event.preventDefault();
  var imgLocation = $(this).attr('href');

  ```js
// Problem: User when clicks an img goes to a dead end
// Solution: Create an overlay with the large img - lightbox

var $overlay = $('<div id="overlay"></div>');
var $img = $('<img>');
$overlay.append($img);
// Add overlay 
$('body').append($overlay);
  // An img
  // A caption

// Capture the click event on a link to the img
$('#img-gallery a').click(function(event){
  event.preventDefault();
  var imgLocation = $(this).attr('href');

   // Update overlay with the link clicked in the link
  $img.attr("src", imgLocation);

  // Get child's alt att and set caption
  $overlay.show();
  // Show the overlay

});

// When overlay is clicked
$overlay.click(function() {
  // Hide overlay
  $(this).fadeOut();
});

// Get child's alt att and set caption $overlay.show(); // Show the overlay

});

// When overlay is clicked $overlay.click(function() { // Hide overlay $(this).fadeOut(); });

1 Answer

As you can see in the line before, you are storing the href attribute of the clicked link in the variable imgLocation.

What the line $img.attr("src", imgLocation); does, is store that href into the source attribute of your overlay's image tag. This means that Every time you click a different image The function will update the imgLocation variable with the href of the new image link and update the image tag's source with that new href.