Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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