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 Perfect

Help

This is not perfect, my code dont work.

// Problem: User when clicking on image goes to adead end //Solution: Create an overlay with the large image - lightbox

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

var $caption = $("<p></p>");

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

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

//2. add overlay $("body").append($overlay);

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

//1.2 Update overlay witht the image linked in the link $image.attr("src",href); }); //1,1 show the overlay. $overlay.show();

//1.3 Get child's alt attribute and set caption var captionText = $(this).children("img").attr("alt"); $caption.text(captionText);

//3. When overlay is clicked $overlay.click(function(){

//3.1 Hide the overlay $overlay.hide(); });

console.log(href);

1 Answer

Tom Sager
Tom Sager
18,987 Points

Are you on this challenge? "Oh no! When you click on an image the browser follows the link. Fix it."

If so, thejQuery event handler will respond to the click, so you need to prevent the default browser behavior (following the link) from occurring. This is covered in the "Perform: Part 1" video.