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 4

Andre Romano
Andre Romano
8,809 Points

jQuery Lightbox hiding overlay

Hey, i just finished jQuery Lightbox lesson by Andrew Chalkley, and I was wondering if there is an easy way to make clicking the image or the caption not hide the overlay, so it only hides if you click on the faded out part?

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

$overlay.append($image);
$overlay.append($caption);
$("body").append($overlay);

$overlay.click(function() {
  // 3.1, hide the overlay
  $(this).hide();
})

That way it would be easier to select and copy the caption text.

Thanks.

3 Answers

Michael Hinrichs
Michael Hinrichs
10,920 Points

I think you can do stopImmediatePropagation() or stopPropagation() on the img or caption.

What this does is keeps the event from traveling up the DOM and having that hide() be triggered.

If you don't do it this way, you have to modify how the overlay is structured...

It's worth a shot! Read up here!

http://api.jquery.com/event.stopPropagation/

You could go the route of adding another div to the lightbox overlay and just change your jQuery around a bit so that when the outer div of the overlay is clicked, the overlay is hidden.

Andre Romano
Andre Romano
8,809 Points

Thanks both for the answers,

That's a really cool solution Michael, it's exactly what i was looking for since i dont have to change the structure of the DOM.

Thanks a lot!