henrymendeez
henrymendeez

Reputation: 27

How to add a fade effect to this JavaScript that hides the navbar on scroll?

I'm following this tutorial from W3 Schools

https://www.w3schools.com/howto/howto_js_navbar_hide_scroll.asp?fbclid=IwAR2u9aQ9iNBivoIPak1btvH3TSLg2WlThLo0QxcWLdcoLefxh55MGT5FOO0

So good so far, everything is working like it should. But, how can I add a fade effect to this JavaScript code?

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

I'm a beginner in this JavaScript world.

Upvotes: 1

Views: 119

Answers (2)

user15517071
user15517071

Reputation: 614

Extending on the example you provided:

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
    document.getElementById("navbar").style.opacity = "1";
  } else {
    document.getElementById("navbar").style.top = "-50px";
    document.getElementById("navbar").style.opacity = "0";
  }
  prevScrollpos = currentScrollPos;
}
body {
  margin: 0;
}

#navbar {
  background-color: #333;
  position: fixed;
  top: 0;
  opacity: 1;
  width: 100%;
  display: block;
  transition: top 0.3s, opacity 0.3s;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 15px;
  font-size: 17px;
}
<div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>
<div style="padding:15px 15px 200px; margin-top:30px;">
<h1>Lorem ipsum dolor sit amet</h1>
</div>

You can use the CSS opacity property to obtain a fade-in effect.

Upvotes: 1

top talent
top talent

Reputation: 599

This work will work in your case.

window.onscroll = fadeIn;
  
function fadeIn() {
    setInterval(show, 200);
}
  
function show() {
  var prevScrollpos = window.pageYOffset;
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

Upvotes: 0

Related Questions