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 trialjohn larson
16,594 Pointsrevisit var inside and outside the function
Someone else asked a similar question and the answer seemed logical at first then I though: Why aren't ALL these variables declared INSIDE the function, cause that's where they are used.
var $overlay = $("<div id='overlay'></div>");
$("body").append($overlay);
$image = $("<img>");
$overlay.append($image);
var $caption = $("<p></p>");
$overlay.append($caption);
$("#imageGallery a").click(function(event){
event.preventDefault();
var imageLocation = $(this).attr("href");
$image.attr("src", imageLocation);
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
$overlay.fadeIn(500);
});
$($overlay).click(function(){
$(this).fadeOut(500);
})
1 Answer
Shane Oliver
19,977 PointsAdding the variables inside the function would mean you are creating the new page elements each time the click function is run. Since you only need to create them once and they are unrelated to the scope of the click function - they should be left outside.
john larson
16,594 PointsSo then ANYTIME we are making what Andrew calls "disembodied elements" such as var $overlay = $(<div></div>);
It should be declared OUTSIDE the function?
john larson
16,594 Pointsjohn larson
16,594 Pointsa little misstep in the code there at the top. $image should be var = $image. other than that, that's pretty much how Andrew has it. $overlay and $image and $caption are declared outside the function. Shouldn't they be declared INSIDE the function?