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

Arsalan Raja
Arsalan Raja
6,508 Points

About .attr

can some one explain to me how $image.attr("src", $imageLocation); code works, its after the click even functions. I am bit confuse about it,

  1. Does it convert image src to href.
  2. Or it linked both together, if yes than how does it find out which pic is clicked, coz its general img selector not ("this")
// Problem: when user clicks on picture it goes to dead end(new page just a pic)
// solution: We need to create overlay of image its called light box of image



  // Add caption

// For overlay we need to add another element like div
var $overlay =  $("<div id='overlay'></div>")
var $image = $("<img>");

// Add image to overlay
$overlay.append($image);
// Add ovelay to the body
$("body").append($overlay);


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

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

})

  // Get child's attribute and add as a caption

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

// Hide the overlay

1 Answer

Hugo Paz
Hugo Paz
15,622 Points

Hi Arsalan,

I edited your post to show the html, please press 'edit post' so you can see what i did.

When you click a thumbnail, you are actually clicking a link ( a anchor tag). That anchor tag href attribute is the path to the image.

So when you click it, this event happens:

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

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

})

We have a jquery object with a list of all anchor elements inside the imageGallery. When we click one, we prevent the default action ( event.preventDefault(); )

We then store the href value in imageLocation. $(this) references the anchor tag you clicked, (the thumbnail).

We now set the src attribute of the image with the href value we stored in imageLocation

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

Then we show the overlay with the full image.