Home > Mobile >  Javacript for Navbar
Javacript for Navbar

Time:01-26

Im creating a navbar. The add javascript to it for two functions. One, the navbar will go invisible when the user scrolls down. Second, the invisible navbar will be visible again if the user reaches the end of the webpage or if they scroll up midway.I can't find the problem in my code, will be helpful if anyone can point it out for me

/ select the navbar element
var navbar = document.getElementById("navbar");

// set a variable to track the previous scroll position
var prevScrollpos = window.pageYOffset;

// listen for scroll events on the window
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;

  // check if the user has scrolled down
  if (prevScrollpos > currentScrollPos) {
    navbar.style.top = "0";
  } else if (currentScrollPos   window.innerHeight >= document.body.offsetHeight) {
    // check if the user has reached the bottom of the page
    navbar.style.top = "0";
  } else {
    navbar.style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
};

CodePudding user response:

The code you provided seems to be on the right track for creating a navbar with the functionality you described. The navbar element is selected, and the onscroll event is being used to track the user's scroll position and make the navbar visible or invisible based on that position.

The main issue I see is that you're using the navbar.style.top property to change the visibility of the navbar. It's better to use a class to change the visibility of the navbar, so you can add CSS styles to control the transition.

You can create a class like "navbar-invisible" and then add and remove the class to the navbar element to change its visibility.

// select the navbar element
var navbar = document.getElementById("navbar");

// set a variable to track the previous scroll position
var prevScrollpos = window.pageYOffset;

// listen for scroll events on the window
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;

  // check if the user has scrolled down
  if (prevScrollpos > currentScrollPos) {
    navbar.classList.remove("navbar-invisible");
  } else if (currentScrollPos   window.innerHeight >= document.body.offsetHeight) {
    // check if the user has reached the bottom of the page
    navbar.classList.remove("navbar-invisible");
  } else {
    navbar.classList.add("navbar-invisible");
  }
  prevScrollpos = currentScrollPos;
};



.navbar-invisible {
  top: -50px;
  transition: top 0.3s ease-in-out;
}

It is important to test this code in different browsers, since browser compatibility can sometimes be an issue when working with JavaScript.

  • Related