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 trialGabriel D. Celery
13,810 PointsHiding overlay issue
Okay so I added this piece of code at the end of the program in order to make the overlay disappear in case I click on it. And it works as intended.
$($overlay).click(function(){
$($overlay).hide();
});
Now the problem is that if I change the code to
$("#overlay").click(function(){
$($overlay).hide();
});
It stops working. Can someone explain to me that what is the reason that changing $overlay to #overlay makes the code not work anymore?
Btw the variable for the overlay div is this:
var $overlay = $('<div id="overlay"></div>');
2 Answers
Jeff Lemay
14,268 PointsWell, in your second function that is not working, shouldn't you be using the #overlay's ID instead of the $overlay variable inside the function?
$("#overlay").click(function(){
$("#overlay").hide();
});
// or you could just use 'this'
$("#overlay").click(function(){
$(this).hide();
});
If you still can't get things to work... Are you inserting the #overlay div after the page is loaded? You'll need to bind the click event to something that already exists on page load. Example:
$('.site-wrapper').on('click', '#overlay', function () {
$('#overlay').hide();
});
Richard Phelps
2,960 PointsWhen you do:
$("#overlay").click(function(){
Do you remove or comment:
var $overlay = $('<div id="overlay"></div>');
Richard Phelps
2,960 PointsRichard Phelps
2,960 PointsThat's exactly what I thought haha. Nice one!
Gabriel D. Celery
13,810 PointsGabriel D. Celery
13,810 PointsThe first two examples given by you don't work either, but the ".on" method does the trick.
Yes, the overlay div is inserted to the html by JavaScript. So I assume this works because the variable was defined inside the JS file.
As for the rest they don't because the overlay wasn't there when the page initially loaded. I think I get it, but its kinda...weird.
Jeff Lemay
14,268 PointsJeff Lemay
14,268 PointsGlad you got things sort of straightened out.