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

CSS jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 3

Why not build out the html for $image entirely within the click function?

Is there a reason the img tag is added to $image and then appended to $overlay outside of the function on click? Is there a disadvantage to doing it like this, within the function?

$("#imageGallery a").click(function(event){
  var imageLocation = $(this).attr("href");

  $image = $('<img>');
  //add image to overlay
  //Update overlay with the image linked in the link  
  $image.attr("src", imageLocation);

  //Show the overlay.  

  //Get child's alt attribute and set caption

1 Answer

Hi Audrey!

The reason you want to build the HTML for $image outside of the click function is because you only want to do it once. Keep in mind that when you're dealing with event handlers, everything inside of the function will run every time the event is fired.

Therefore, if the construction and appending of the HTML img element existed inside the function, a new img element would be built and appended every time we clicked on an anchor element. If we clicked 5 times, we'd have 5 img elements when we only wanted one!

All we really want the function to do is dynamically pass in the appropriate href values to the one img element that exists, and then show the overlay.

Does that make sense? It's been a while since I took this course so I'm probably a bit rusty on the details.



Makes total sense. Now that you said it, I'm having a "duh" moment. Thanks!

It's things like that which would be super handy to include in the videos... more of the WHY, instead of just "type along with me as we do A, B, C". That goes double for "why event is passed to the function" and "what the event object is. I happened to know about the event object prior to that video, but if people are starting out with just the JS Intro course under their belts, it hasn't been mentioned before, much less used. I noticed many people asked about it in the questions.