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

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

Shiraj Ganguly
Shiraj Ganguly
12,608 Points

Why doesn't using a jQuery selector let me hide the overlay? [jQuery Basics - Perform: Part 3]

In this lesson why does the following code work:

var $overlay = $('<div id='overlay'></div>');

$overlay.click(function(){
$(this).hide()};

But this does not (assuming a div with id of overlay has already been appended):

$("#overlay").click(function(){
$(this).hide();)};
Sam Hayward
Sam Hayward
11,673 Points

Hi =) I am having the same problem :( I even copied and pasted the project files into workspaces. The image and overlay appear when you click an image, but then does not disappear when the overlay is clicked. So could there be something wrong with my browser? I'm using Chrome Thanks =)

Edit* I tried again later and it worked even though i didn't change anything - any ideas why this might have happened?

3 Answers

Shiraj Ganguly
Shiraj Ganguly
12,608 Points

Thanks for the reply! The missing ) was my mistake, I was trying to retype my code vs just pasting it in. It still doesn't work though.

Why does the code work when I use:

$overlay.click(function(){ 
    $(this).hide();
});

but not when I use:

$('#overlay').click(function(){ 
    $(this).hide();
});

Aren't these equivalent?

Andrew Chalkley
Andrew Chalkley
Treehouse Guest Teacher

They are almost equivalent.

It depends - have you appended the $overlay before you call:

$('#overlay').click(function(){ 
    $(this).hide();
});

If the overlay doesn't exist yet it can't bind to it.

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

You're missing a ) somewhere :)

You can use a tool like this http://javascriptlint.com/online_lint.php to help you spot errors in your code.

James Barnett
James Barnett
39,199 Points

I like doing practice in JSBin because it auto-lints and I can run the code right there. It also has a built-in console tab that makes it easier when doing exercises that have lots of console.logs.

Andrew Chalkley
Andrew Chalkley
Treehouse Guest Teacher

No worries.

Just think about the order your code is executed.

In the final stage I show a magical method that you can use to bind to elements that haven't been added to the DOM yet. Keep an eye out for it :)