Home > Back-end >  Hide navbar as scroll down | Vue 3
Hide navbar as scroll down | Vue 3

Time:11-18

I'm student, I work with VueJs using Script Setup syntax.

I'm trying to hide a navbar while scroll down and make it appears while scroll top. It seems the issue come from previousScrollTop. When I console.log(previousScrollTop) its value is exactly the same as ScrollTop.

To make it works, I need previousScrollTop value lower than ScrollTop value. I've tried many way but did not work. Can you please help me? If you have any suggestions to improve my code do not hesitate =)

Here is my code:

const manageNavBarAnimations = () => {

  const header = document.querySelector("header");
  const scrollTop = document.documentElement.scrollTop;
  const previousScrollTop = scrollTop;

  console.warn(previousScrollTop);
  console.log(scrollTop);

  if (scrollTop > previousScrollTop) {
    header.style.top = "-80px";
  } else {
    header.style.top = "0";
  }
};
header {
  @apply fixed right-0 left-0 z-50 bg-slate-900;
}
<template>
  <header @scroll="manageNavBarAnimations">
    <main-nav-organism></main-nav-organism>
  </header>
</template>

CodePudding user response:

You assign previousScrollTop directly after assigning the scrollTop value, so obviously the two values are always identical. You have to assign your scrollTop value to your previousScrollTop variable AFTER having done some checking and handling of the error cases of the first pass (either check that the previousScrollTop value does not exist, or assign it a default value at the beginning)

Also, you have to create your previousScrollTop variable outside your function if you want its value to persist between calls. I invite you to read about the different scope and range of variables

 let previousScrollTop;

const manageNavBarAnimations = () => {

  const header = document.querySelector("header");
  const scrollTop = document.documentElement.scrollTop;
 


  if (scrollTop > previousScrollTop || !previousScrollTop) {
    header.style.top = "-80px";
  } else {
    header.style.top = "0";
  }

  previousScrollTop = scrollTop
};
  • Related