CharlyAnderson CharlyAnderson - 4 months ago 28
CSS Question

Sticky header - calculate screen size

I am stuck and hoping someone might be able to help me. There are tonnes of tutorials / examples of making a header stick on scroll for fixed height headers.

However, I am working on a one page website and the initial section is a full screen image. The user then scrolls down to reveal the header and other content areas.

So my question is, how can I change my code to take into account the viewport / screen size - rather than use a fixed header size?

My existing code is:

$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 65) {
$(".main").addClass("sticky");
} else {
$(".main").removeClass("sticky");
}
});


Thanks in advance to any help you can give me

Answer

You could use the height of the window instead of a fixed value (since you're talking about a full screen image, I'm guessing its height is equal to the window height):

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= $(window).height()) {
        $(".main").addClass("sticky");
    } else {
        $(".main").removeClass("sticky");
    }
});

You could also get the height of the first section, if it's smaller than the window