Pergunta

I want to hide my Bootstrap-Navbar on the first section of my one-page site and fade it in when scrolled past this first section.

I tried using the jQuery .hide() effect, telling it to hide the navbar when scrollTop is < 300px and fade it in below - this works fine but the first time the page loads the navbar is not hidden, just after I scrolled down the first time and I can't figure out why.

Here is my code :

$('#wrapper').scroll(function(){
if($(this).scrollTop() < 300) $('#navbar').hide('easing');
if($(this).scrollTop() > 300) $('#navbar').fadeIn('slow');
});

Here is the jsfiddle

How can i do this ?

Foi útil?

Solução 5

Try with this

HTML

<div id="navbar" style="display:none">Teasers Div</div>

Script

$( document ).ready(function() {
  $('#wrapper').scroll(function(){
  if($(this).scrollTop() > 300) 
    $('#navbar').fadeIn('slow');
  else
    $('#navbar').hide('easing');
  });
});

DEMO

Outras dicas

I think it's becuase the #navbar element is not initially hidden.

Just hide it using css:

#navbar {
    height:50px;
    background-color:green;
    position:fixed;
    top:20px;
    width:100%;
    display: none;
}

Demo: http://jsfiddle.net/Ub4xm/17/

You should set the bar to hide on startup, either in CSS (clean) or in HTML (quick-and-dirty).

The jQuery's .hide() sets the display to "none" if I'm correct, so set the display on page load to "none", since .fadeIn() will set the display to "block".

add display to none:

#navbar {
  height:50px;
  background-color:green;
  position:fixed;
  top:20px;
  width:100%;
  display:none; /* <--add this*/
}

or in your js you can trigger your .scroll() in the doc ready:

$(document).ready(function () {
  $('#wrapper').scroll(function () {
     if ($(this).scrollTop() < 300) {
         $('#navbar').hide('easing');
     } else if ($(this).scrollTop() > 300) {
         $('#navbar').fadeIn('slow');
     }
  }).scroll(); // <-----trigger it here first.
});

The above code let you see the hide with easing when doc is ready.

first hide #navbar in load time .

$( document ).ready(function() {

    $('#navbar').hide();

    $('#wrapper').scroll(function(){
      if($(this).scrollTop() < 300) $('#navbar').hide('easing');
      if($(this).scrollTop() > 300) $('#navbar').fadeIn('slow');
    });
});

demo

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top