Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hide navbar as scroll down | Vue 3

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 =)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading