Javascript attribute based on position scroll does not return to original state when scrolling backup

See JSFiddle here: http://jsfiddle.net/jL6d2qp6/

I have an animation that should contain the #top element in a fixed position at the top of the page, except when the #login element is on the screen. To control this, I use a javascript function that runs every 10 ms and disables the css class for #top, and when I scroll down, it updates as expected, but when I try to scroll, nothing happens.

Javascript code in question:

offScreen = function(id, targetValue)
{
    var offset = $("#top").offset();
    var w = $(window);
    var height = $(id).innerHeight();
    var finalOffset = (offset.top + height) - w.scrollTop();
    if (finalOffset < targetValue)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function updateTopMenu()
{
    if (offScreen("#login", 81) === false)
    {
        if($("#top").hasClass("top-bar-absolute") === false)
        {
            $("#top").addClass("top-bar-absolute");
            console.log("added top-bar-absolute");
        }
        if($("#top").hasClass("top-bar-fixed") === true)
        {
            $("#top").removeClass("top-bar-fixed");
            console.log("removed top-bar-fixed");
        }
    }
    if(offScreen("#login", 81) === true)
    {
        if($("#top").hasClass("top-bar-absolute") === true)
        {
            $("#top").removeClass("top-bar-absolute");
            console.log("removed top-bar-absolute");
        }
        if($("#top").hasClass("top-bar-fixed") === false)
        {
            $("#top").addClass("top-bar-fixed");
            console.log("added top-bar-fixed");
        }
    }
}

$("#top").ready( function() {
    setInterval(updateTopMenu, 10);
});

Also, if there is a better way to accomplish this, I would like it because it seems clean.

+4
1

- . , . , , .

, #top box .sticky, position: fixed. .

jsFiddle.

+1

Source: https://habr.com/ru/post/1568080/


All Articles