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

Why wouldn't $("#overlay").remove() work instead?

I tried to recreate this as an exercise, and I wanted to know why the following code wouldn't work:

 var $imageLinks = $("#imageGallery a");

 $imageLinks.click(function(event){

    event.preventDefault();
    $("body").append("<div id=\"overlay\"></div>");

 });

 $("#overlay").click(function(){

    $("#overlay").remove();
    console.log("Removing...");

 });

Is this because the element has to be in the DOM for jQuery to recognize it? This is my best guess, do all elements need to be put in the DOM before jQuery can interact with then, so you can't simply add and remove, rather show and hide? Thanks!

1 Answer

I think the problem is in the order of execution for your code; when your code initially runs, the $imagelinks variable is first set, then your click handler is registered, then your $('#overlay') selector is finally called but nothing is found (because the div hasn't been appended yet!) so the handler is not registered. You need to include the click handler on the overlay after it's appended as such:

var $imageLinks = $("#imageGallery a");

$imageLinks.click(function(event){
    event.preventDefault();
    $("body").append("<div id=\"overlay\"></div>");

    $("#overlay").click(function(){
        $("#overlay").remove();
        console.log("Removing...");
    });
});

That makes sense! I didn't think of inserting the query inside the other, right after the overlay is appended.

Minor question, but is it better to add something, and then hide/show in the video, or append/remove? It seems like a manner of context, but my guess is that it's better to hide/show, because it would probably be faster, and it seems to result in cleaner code...? Just trying to get into the jQuery workflow, thanks!