The functionality of displaying the header when scrolling up and hiding it when scrolling down is not functioning as expected when using the

I am interested in implementing a scroll event to the window object that will display the header when scrolling up and hide it when scrolling down, but only after everything has finished loading.

However, I am encountering an issue where sometimes the hide class is added to the header when I refresh the page, even though it shouldn't be. How can I go about resolving this problem? Below is the code snippet:

document.addEventListener('DOMContentLoaded', () => {
  window.onscroll = function (e) {
    if (this.oldScroll > this.scrollY) {
      header.classList.remove('hide');
    } else {
      header.classList.add('hide');
    }
    this.oldScroll = this.scrollY;
  };
});

Answer №1

The reason for this issue is that the condition is false when the page loads, triggering the else statement. To prevent this, you should consider using an else if statement. Here's how you can modify the code:

document.addEventListener('DOMContentLoaded', () => {
  window.onscroll = function (e) {
    if (this.oldScroll > this.scrollY) {
      header.classList.remove('hide');
    } else if (this.oldScroll < this.scrollY) {
      header.classList.add('hide');
    }
    this.oldScroll = this.scrollY;
  };
});

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

Using JQuery to toggle visibility - select and toggle between next and previous classes based on click event

I need to simplify the creation of an image slider I am working on. Currently, my method requires entering too many combinations. Here is what I have so far: <script> $(document).ready(function(){ $('#1').show(); ...

PHP Tutorial: Dynamically Adding or Removing Divs Based on Checkbox Selection

Check out this code snippet: <div id="product"> <b>SELECT PRODUCT:<br></b> <input type="checkbox" name="fruits" value="1">Orange<br> <input type="checkbox" name="fruits" value="2">Grapes<br> <input type=" ...

How do I create a specific onShow onHide event in jQuery for a single targeted element?

I have implemented the following code to trigger on-show and on-hide events. This allows for automatic execution of custom functions when a DIV becomes visible, making necessary changes at that moment. (function ($) { $.each(['show', &apo ...

Is there a way for me to ensure that a response is only returned once a method call has been completed in

Seeking assistance with a Node.js application using Express. I am trying to create a REST endpoint that returns the response of an HTTP call. However, no matter what I attempt, it always returns before the HTTP request has completed. Can anyone provide g ...

The rows-per-page menu option in Vuetify suddenly vanishes

I'm currently working on incorporating a v-data-table inside a v-card, you can view the code in this CodePen snippet: https://codepen.io/benwasin97/pen/eYveZGL <v-data-table :headers="headers" :items="items" ...

What is the best way to divide this string with jQuery?

Is there a way to use jQuery to split this specific string? "[10.072721346470422,76.32974624633789][[10.075854059674523,76.32043361663818],[10.073650930297095,76.32888793945312],[10.074918540288232,76.33090496063231],[10.073862198974942,76.33137702941895] ...

When toggling visibility with JS, the Bootstrap Grid Row may not center-align as expected

Sorry for the odd spacing issue that might occur. I currently have a basic Bootstrap Grid setup as follows: <div class="row justify-content-center" align="center" id="details"> <div class="col-sm-2"> ...

Tips for concealing the CSS style of a descendant span element when the parent div employs text-overflow: ellipsis

Is it possible to prevent the green background of a child span from showing when the parent span has text overflow ellipsis applied? .container { border : 1px solid black; max-width : 100px; overflow : hidden; text-overflow ...

The AutoComplete feature in Formik Field from Material UI component is not showing the InitialValues

Having an issue with displaying the initialValues in the AutoComplete component from the Material UI library when used in a Formik Field. Even though values are passed as initial, they do not render in the component, although if the form is submitted, they ...

What is the process for converting this value to a floating point

Here is the code snippet I am working with: $wage = array(); foreach ($result3 as $row3) { $wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']'; } if ($userid == 0 ) { $age= ""; ...

There seems to be an issue with the React-Heroku Postgres-Addon: when trying to access http://app-name.herokuapp.com/any, a

I've been working on deploying a CRUD todo-list app to Heroku using React, NodeJS, and the Postgres Addon from Heroku. Although there were no errors during deployment, it appears that the front-end is not properly connected with the back-end. When att ...

Troubleshooting Variable Issues in PHP and JavaScript

On my PHP page, I have a while loop where I am retrieving the following... print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id=&apos ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

Reveal and Conceal accordion elements

https://i.sstatic.net/y4KNM.png I am looking to create an accordion effect similar to the one shown in the image. When a lesson is completed, it should hide and display the next lesson in line. Additionally, I want to ensure that only one accordion remain ...

PHP Solution: I'm working on a page that is accessed using the post method. However, I need to defer the execution of certain code until after the page has finished

Apologies for the confusing title, but I'm struggling to succinctly explain my issue: I have a web page that is accessed through a button. When this button is clicked, specific data (a unique identification name) is sent to the page I want to view. Ho ...

Tips for setting elevation breakpoints for Paper components in MUI

I'm currently utilizing the MUI5 framework for my Project and I must say it's been great so far. I recently created a login page where I incorporated the Paper Component. Within the Paper Component, I wanted to specify an Elevation level. This i ...

The PHP-generated form is not able to submit via AJAX

My select element includes ROWID in the value along with a name in the value field. <select name="opcoes" onchange="showInfo(this.value)"> <option value=''>Select</option> <option value=6>A</option> <option valu ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Is there a way to transfer the getJSON output into an input field?

I am attempting to fill out a form with the data from the most recent entry in my database using $.getJSON. Although the GET request successfully returns the JSON, I am struggling to populate the fields with the data. I am relatively new to this and seekin ...

Techniques for extracting a specific section of a string in Javascript

On another web page, I am extracting a specific string. My goal is to store that string in a variable after a specific point. For example: #stringexample var variable; I need the variable to only include "stringexample" without the # symbol. How can I a ...