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

Pavel Makeev
Pavel Makeev
6,207 Points

Don't understand the small part of code. Please, Help

So here I can't understand the part starting with //Capture the click event on a link to an image and endig with // Update overlay with the image in the link. Can someone explain what this code does in details?

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

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

// An image to overlay $overlay.append($image); // A caption // When the overlay is clicked

//Capture the click event on a link to an image $("#gallery a").click(function(event){ event.preventDefault(); var imgLocation = $(this).attr("href"); // Show overlay $overlay.show();
// Update overlay with the image in the link $image.attr("src", imgLocation);

// Get child's alt and set caption });

// Get rid of the overlay $overlay.click(function(){ $(this).hide(); });

1 Answer

//Capture the click event on a link to an image
$("#gallery a").click(function(event){   //<-- your image link is clicked
event.preventDefault(); //<-- the default behaviour of link click is prevented, so it won't open in a new tab like itby default would
var imgLocation = $(this).attr("href");  //<--this saves the url from the href attribute of the clicked link to a variable called imgLocation
$overlay.show(); <-- the overlay is shown
$image.attr("src", imgLocation); //<-- the src attribute of the overlay image is updated with the  url from the href attribute of the clicked link