change element class on scrolling up and down?

Viewed 71

My problem is exactly that, when the specified part (JavaScript if) is executed, it disables my function.

See my problem in the console by scrolling.

I want it to have output on the console while scrolling. I want it to run again when the page is scrolled up (if).

With each scroll, the function must be executed. But after adding the class in (if specified) the function closes. I am a beginner. Maybe I can not explain well. Please see the code below and help me.

    var position = $(window).scrollTop();
    
    window.addEventListener("scroll", function () {


        var elemChoose = $("#fix-menu-top").offset().top + $("#fix-menu-top").innerHeight();

        var scroll = $(window).scrollTop();
        
        if ($(window).scrollTop() > elemChoose) {

            console.log("functionCalled");

            if (scroll >= position) {
                if ($("#fix-menu-top").hasClass("fix-visible")) {
                    $("#fix-menu-top").removeClass("fix-visible")
                }
            }
            // The problem arises after running this. Down if
            if (scroll < position) {
                if (!$("#fix-menu-top").hasClass("fix-visible")) {
                    console.log("run");
                    $("#fix-menu-top").addClass("fix-visible")
                }
            }
            // The problem arises after running this. top if
        }
        position = scroll;



    });
.container-navigation.fix-hidden#fix-menu-top {
    border-top: 1px solid #f0f0f0;
    position: fixed;
    top: -10%;
    left: 0;
    right: 0;
    background: red;
}

.container-navigation.fix-visible#fix-menu-top {
    border-top: 1px solid #f0f0f0;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body style="height: 2000px;">

  <div class="container-navigation" id="fix-menu-top"></div>

</body>
</html>

0 Answers
Related