Conceal navigation bar when scrolling | Vue 3

I am a student working with VueJs using the Script Setup syntax.

My goal is to hide the navbar when scrolling down and make it appear when scrolling to the top. The issue seems to be related to the previousScrollTop variable. When I console.log(previousScrollTop), its value is always the same as ScrollTop.

To achieve the desired functionality, I need the previousScrollTop value to be lower than the ScrollTop value. I have tried various approaches but none have worked. Can you please assist me? Any suggestions to improve my code would be greatly appreciated =)

Below is the code snippet:

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>

Answer №1

After setting the scrollTop value, you must set the previousScrollTop variable to avoid always having identical values. Make sure to handle error cases and check if the previousScrollTop value exists before assigning it a default value at the beginning.

Furthermore, for the value of previousScrollTop to persist between function calls, declare the variable outside the function scope and review the concept of variable scope in programming.

 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
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the Expo camera struggle to save photos to the gallery? It should be a simple task

I'm having an issue where I can successfully take a picture with a preview, but it's not saving to the gallery. Even after adding MediaLibrary.createAssetAsync, the image preview doesn't show up and the picture still isn't saved loca ...

Implementing a comprehensive Node application with a fully stacked npm and package.json structure

If there's a repository with both backend (Node/Express) and frontend client, the structure might look like this: ├── build ├── config ├── coverage │ └── lcov-report ├── dist │ └── static ├── server ( ...

Designing Angular2 application structure for various platforms (web, mobile, native)

Imagine an ng2 application that caters to multiple platforms such as web, mobile-web, and mobile-native. Due to the presence of shared files like action creators, reducers, services, and common components across these platforms, it's feasible to have ...

React and TypeScript threw an error: trying to execute setSearchQuery, which is not a function

I encountered an issue where I am receiving the error message: Uncaught TypeError: setSearchQuery is not a function in my Next.js / Typescript app. This error occurs while typing a search query into the search box. I have implemented a generic search funct ...

How can I use nodejs to retrieve all data fields from a table except for one specific field?

Is there a way to fetch all fields data from a table without specifying the field names or creating a view? I have attempted the following SQL query: WITH orderschema as (SELECT array_to_string(ARRAY(SELECT c.column_name FROM information_schema.co ...

The sequence of CSS rules in the webpack build may vary compared to development

I'm facing a dilemma whether this issue stems from webpack, vue-loader for webpack, or an error on my part. Whenever I run npm run build to create a distribution for my Vue.js application, the CSS rules applied in the dist app are ordered differently ...

"Step-by-step guide on using JavaScript to print a PDF file stored locally

As an illustration, I have a local PDF file with 6 pages. When using the window.print() function, only one page is displayed in print preview regardless of what is shown in the browser. Instead of just one page, all pages should be visible in print previ ...

What causes a syntax error when trying to create an array of objects within a map using colons?

In my Google Apps Script, I created a function to retrieve the date and subject of emails with a specific label in Gmail. However, when attempting to store each result as an object, I encountered a SyntaxError: unexpected token ':' issue. Althoug ...

Issue with CSRF token not found when using vue-recaptcha alongside a Django Rest Framework middleware

In my current setup, I have: A frontend application built with VueJS that includes a registration form component. The form consists of standard fields, a mandatory checkbox for user agreement, and a Google Recaptcha V2 checkbox implemented using vue-recap ...

The Ajax success callback is failing to update the background-image property after receiving a successful JSON response

I am struggling with setting a background image in wordpress despite receiving a successful ajax response. The image url is being returned successfully in the json response, but I can't seem to set it as a background image. Here is the ajax function ...

Is Your Website Optimized for All Devices?

Creating this website was just a little project for me. I've been experimenting with different methods to ensure it's compatible with all devices and fits perfectly on each screen. Unfortunately, I'm pretty clueless when it comes to @media ...

Steps to ensure an npm script completes all tasks before ending, regardless of any task failures

My NPM script is set up to run multiple tasks like this: "multiple": "task1 && task2 && task3" Unfortunately, if task2 encounters an error, the script will stop and task3 won't get executed. I'm wondering if ...

Guide on linking JavaScript files in Node.js

I am having trouble getting my javascript to work properly. My javascript files are located in the public/javascripts directory. app.js app.use(express.static(path.join(__dirname, 'public'))); views/layout.pug doctype html html head ti ...

Can you identify the origin of the inclusion of a .php file?

Is there a way to automatically determine if a PHP script is being accessed directly as an HTML page, used as a JavaScript file, or utilized as a CSS Stylesheet? I'm looking for a solution that doesn't involve GET variables or setting a flag wit ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

I encountered a 429 error while trying to make a request to the Spotify API

I recently encountered an issue with my website where I am trying to retrieve and display my playlists. Everything was working fine yesterday, but this morning I started getting error 429 every time I tried to retrieve data from the api, even though I have ...

Angular data binding is a concept that continues to elude me

After spending countless hours experimenting with variations of this code, it remains a mystery to me why one version works while the other fails. The situation is as follows: I am attempting to display a list of registered users retrieved from a database ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

Stop the rendering of ANGULAR pages in case the NODE proxy is not operational

Looking for a solution to always redirect to an Angular page displaying "Server Down! Sorry!" if the Node proxy is not running. I want to restrict access to more secure pages when the Node proxy is not up. Considering using HTTP status, but wondering if t ...

The process of retrieving a JavaScript value using AJAX

I'm working on a code snippet that looks like this: $(document).ready(function() { $('#myHref').change(function(){ var value = $('#myHref').val(); $.get('get_projectName.php',{id:value},function(data) ...