Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Matthias Nörr
Matthias Nörr
8,614 Points

Overlay of Lightbox not showing. Images are just added after the body (Course: jQuery Basics, Simple Lightbox)

When an image in the gallery is clicked, no overlay is shown. Instead, the image is shown below the body of the page.

Javascript:

var $overlay = $('<div class="overlay"></div>');
var $image = $("<img>");

$("body").append($overlay);
$overlay.append($image);

$(".container_1 a").click(function(event){
    event.preventDefault();                         //Prevent Default Click Behaviour
    var imageLocation = $(this).attr("href");       //
    $image.attr("src", imageLocation);

    $overlay.show();                                //Show Overlay on Click
});

$overlay.click(function() {                         //Hide Overlay on Click
    $overlay.hide();    
});

CSS:

.overlay {
    background: rgba(0,0,0,0.7);
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    display: none;
    text-align: center;
}
Joel Bardsley
Joel Bardsley
31,242 Points

Hi Matthias,

Everything looked fine to me, so I created a CodePen using your code (and a few placeholder images) to make sure it was working properly, which as you can see it is.

All I can suggest is making sure jQuery has been loaded properly from your HTML file, or ensuring there's nothing else using a z-index property in your css that might be preventing the overlay from appearing on top.

2 Answers

Matthias Nörr
Matthias Nörr
8,614 Points

Thanks Joel. This allowed me to rule out some causes for the problem.

I solved my problem. Here is the solution:

Append the overlay to the html-tag and not to the body-tag

$("html").append($overlay);

and not

$("body").append($overlay);
Matthias Nörr
Matthias Nörr
8,614 Points

Joel Bardsley The lightbox overlay stops at the screen. When I scroll down in the browser, the overlay does not cover all of the screen but stops. Do you know how I can fix this?