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 1

Trouble with "this" and e.target

I have been using arrow functions consistently and when I do this with this code it logs "undefined"

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

//1, Capture the click event on a link to an image
$("#imageGallery a").click(e => {
    let href = $(e.target).attr('href');
    //1.1, Show the overlay
    //1.2, Update overlay with the image linked in the link
    //1.3, Get child's alt atribute and set caption
//2, Add overlay 
    //2.1, An image
    //2.2, A caption
//3, When overlay is clicked 
    //3.1, Hide the overlay

1 Answer

28,538 Points

this within regular jQuery functions is equivalent to e.currentTarget not e.target. So if you use e.currentTarget like this:

$("#imageGallery a").click(e => {
    let href = $(e.currentTarget).attr('href');

Then the code will work.

The difference between currentTarget and target is that currentTarget will always refer to the element that the event listener is attached to, the a elements in this case. Whereas target refers to the element that actually triggered the event, which in this case is the img elements inside the a elements.

This is simple the way you explained! Thanks alot this really helps.