Giuseppe Giubaldo Giuseppe Giubaldo - 4 months ago 7
CSS Question

css/jquery scroll-fixed div issues

I'm trying to fix a div after a certain pixels when the window's browser scrolls down and after, when the window scrolls up, put the div in the same position at the beginning.

$(window).scroll(function () {
var button = $('.button-mobile');
offset = button.offset().top;
position = button.position().top;
console.log(position);
if ($(this).scrollTop() >= offset) {
$('.button-mobile').css({
"max-height": "100%",
"position": "fixed",
"overflow-y": "auto",
"top": "40px",
"z-index": "1"
});
} else {
$('.button-mobile').css({
"position": "absolute",
"top": "none",
"overflow-y": "none",
"z-index": "none"
});
}
});


If branch works well.
Else branch is the problem, i think.

This branch is a test for a precedent experiment.
Else branch works with known height in px but not with the offset that change frequently.

Also I don't know why when the window scroll down to the div the position's top value is set to 40px.

Thanks

Answer

I suppose you should move button and offset assignment out of scroll callback:

    var button = $('.button-mobile');
    var offset = button.offset().top;

    $(window).scroll(function () {
        position = button.position().top;
        console.log(position);
        if ($(this).scrollTop() >= offset) {
            $('.button-mobile').css({
                "max-height": "100%",
                "position": "fixed",
                "overflow-y": "auto",
                "top": "40px",
                "z-index": "1"
            });
        } else {
            $('.button-mobile').css({
                "position": "static",
                "top": "none",
                "overflow-y": "none",
                "z-index": "none"
            });
        }
    });
Comments