How to set a menu with jQuery?

0

I'm a beginner and would like to know 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 ".topo" header to only appear when the user scrolls.

But, as you can see on the site ( link ), once the site is loaded, the header appears (when it should be hidden until that there was a scroll bar down) and went back to being hidden if the user returned 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>
    
asked by anonymous 21.03.2016 / 23:48

1 answer

2

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

Change this:

<div class="topo fixar">

So:

<div class="topo">

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

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

    
22.03.2016 / 00:16