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 trialcassac
9,628 PointsThe append() method called on the body does't work until its called within the click() method. What gives?
Code in video...
var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
$overlay.append($image);
$("body").append($overlay);
$("#imageGallery a").click(function(event){
event.preventDefault();
var imageLocation = $(this).attr("href");
$image.attr("src", imageLocation);
$overlay.show();
});
The above code doesn't work until I move $("body").append($overlay);
var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
$overlay.append($image);
$("#imageGallery a").click(function(event){
$("body").append($overlay);
event.preventDefault();
var imageLocation = $(this).attr("href");
$image.attr("src", imageLocation);
$overlay.show();
});
cassac
9,628 PointsThe div is appended to the body before the <a> tags are clicked, therefore displaying the dark transparent background from the beginning. There aren't any errors in the javascript console. I'm not too familiar with jQuery, what would I be console logging?
Mark VonGyer
21,239 PointsI have a sneaky suspicion it is to do with the $overlay.show() line
2 Answers
Ebrahim Haji
6,712 PointsJust fork your workspace
Tyron Wytrykowski
Courses Plus Student 3,105 PointsI had the same problem. It turns out I forgot to add : display:none; in the #overlay selector in the style.css file.
Mark VonGyer
21,239 PointsMark VonGyer
21,239 Pointshave you tried the javascript console to see what is happening?
You could put a console.log message after the first attempt to see if it is processed.
Also check for errors on console.