Fixed menu after scrolling

Asked

Viewed 2,635 times

1

I want to get the menu fixed after certain scrolling,

 <script>
    $("document").ready(function($){
        var nav = $('.menu-topo');

        $(window).scroll(function () {
            if ($(this).scrollTop() > 150) {
                nav.addClass("fixo");
            } else {
                nav.removeClass("fixo");
            }
        });
    });
</script>

and html

<div id="menu-topo">asdasdasd</div>

It’s not getting fixed. What’s wrong?

2 answers

1

You are using menu-topo as id and selector is searching for class .menu-topo instead of #menu-topo.

  • 1

    The variable nav there is a jquery object of length 0. Checking the length before continuing to develop is interesting not to happen this type of error.

0

There is a much easier and simpler way to do this using just one property of css called Position: sticky.

div.sticky {
   position: -webkit-sticky;
   position: sticky;
   top: 0;
   padding: 5px;
   background-color: #cae8ca;
   border: 2px solid #4CAF50;
}

<div class="sticky">MENU</div>
  • It didn’t happen this morning, I tried here and nothing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.