How to fix a menu with jQuery?

Asked

Viewed 97 times

0

I am beginner and I would like to know what the error of this code:

var nav = $('.topo');

$(window).scroll(function () {
    if ($(this).scrollTop() > 136) {
        nav.addClass("fixar");
    } else {
        nav.removeClass("fixar");
    }
});

The idea was for the header ". top" only to appear when the user scrolls.

But as you can see on the website ( http://www.williamgama.com ), as soon as the site is loaded, the header appears (when it should be hidden until there is a scrollbar drive down) and is hidden again if the user returns to the top of the page.

.topo {
        display: block;
        width: 100%;
        height: auto;
        background: transparent;
        z-index: 3;
}

.fixar {
        position: fixed;
        margin: 0;
        top: 0px !important;
        height: 64px;
        background: rgb(255, 255, 255);
        display: block;
        overflow: hidden;
        box-shadow: 0 7px 7px rgba(0, 0, 0, 0.1), 0 7px 7px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease-in-out;
        -webkit-transition: all 0.2s ease-in-out;
}

html:

<div class="topo fixar">

  <img src="img/logo/logo.svg">

  <nav class="menu-web position">

    <ul>
      <li><a href="#inicio">Início</a></li>
      <li><a href="#o-estudio">O Estúdio</a></li>
      <li><a href="#atuacao">Atuação</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#depoimentos">Depoimentos</a></li>
      <li><a href="#sobre-william">Sobre William</a></li>
      <li><a href="#contato">Contato</a></li>
    </ul>

  </nav>

</div>

1 answer

2


You are starting HTML with the class .fixar. Remove it from your html and everything should be resolved.

Change this:

<div class="topo fixar">

That’s why:

<div class="topo">

Explaining: There is no error in your code that is managing the class to set the menu. What happens is that the jQuery is in charge of adding the class dynamically, so you don’t have to worry about it. Just set the initial menu style and let the jQuery add the class to make it fixed.

If you notice it well on your site, it starts with the class fixar but if you do a small scroll, it will be removed and will only be added again after passing the 136px distance from the top you set.

  • Thank you very much, Celsom! Excellent explanation.

  • Access and see the final result: www.williamgama.com All thanks to your collaboration. Thank you again, brother.

Browser other questions tagged

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