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 Preventing the Default Behavior and Using attr()

Rachel Alexander
Rachel Alexander
4,425 Points

jQuery lightbox code challenge

The task is to specify the href attribute for the clicked link. This is what I have:

//Problem: User when clicking on image goes to a dead end
//Solution: Create an overlay with the large image - Lightbox

//1. Capture the click event on a link to an image
$("#imageGallery a").click(function(event){
    var href = $(this.attr("href"));
  //1.1 Show the overlay.
  //1.2 Update overlay with the image linked in the link
  //1.3 Get child's alt attribute and set caption


Using this code, I'm getting an error that task 1 (the prevent default event behavior line above) is no longer passing with the href variable definition I've put in, even though task 1 passes fine when I go back to it with both lines of code in place.

I found someone with a similar issue on the forum, but as far as I can tell, my code is identical. I've re-typed the line from scratch and it's still not working. Any ideas what might be wrong?

2 Answers

Mike Costa
Mike Costa
Courses Plus Student 26,362 Points
 var href = $(this.attr("href"));

The problem is with this line. When you're chaining a function on an object, you need to attach the function to the object. $(this) would be the object, and attaching the function .attr() to it would be chaining it. You attached the function inside of the jquery selector.

Rachel Alexander
Rachel Alexander
4,425 Points

That did the trick. Thanks!

For anyone else who runs into the same issue, the correct code would be:

var href = $(this).attr("href");

I am making the quiz in the exact same way and still no resolve. var href = $(this).attr("href");