Is there a way to stop window.pageYOffset from resetting every time the page is rendered?

I've been working on a react component that changes the header based on the scroll event. By attaching an event handler and toggling a display class to show or hide certain elements depending on the scroll position.

However, I've encountered some glitchy behavior whenever the component tries to re-render. You can see an example in the codesandbox link provided below.

import React from "react";
import "./styles.css";

export default function App() {
  const [scrollY, setScrollY] = React.useState(0);
  React.useEffect(() => {
    const handleScroll = () => {
      console.log(window.pageYOffset);
      setScrollY(window.pageYOffset);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, [setScrollY]);

  const scrolled = () => scrollY > 40;

  return (
    <div className="App">
      <div className={`header ${scrolled() ? "d-none" : ""}`}>Header Main</div>
      <div>
        <div className={`header-secondary ${scrolled() ? "d-none" : ""}`}>
          Header Secondary
        </div>
        <div className={`header-scrolled ${!scrolled() ? "d-none" : ""}`}>
          HeaderScrolled
        </div>

        <div>Scroll Position: {scrollY}</div>
        {[...Array(100)].map((e, i) => (
          <div>
            <div className={scrolled()}>{`SCROLLING`}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Link to my codesandbox: https://codesandbox.io/s/wizardly-saha-0oklr

I've noticed that the hide/unhide component condition is set at 40px. When scrolling slowly around 40px, the header snaps back and the window.pageYOffset gets reset to 0. I'm puzzled by this behavior and can't seem to figure out why it's happening?

If you scroll past fast enough, it doesn't seem to have an impact, but there's certainly some odd behavior occurring around the display class toggle.

EDIT: Updated Example What I'm essentially trying to achieve is a smooth transition from the Header Main to the Header Secondary. Unfortunately, I can't modify the styling on Header Main as it's not within my control.

Answer â„–1

The issue at hand revolves around the header of your webpage. When you are at the top of the page, the header's position relative affects the height of the scrolling body. However, as you start to scroll down, the header becomes fixed and no longer impacts the body. Upon scrolling back to the top, the header once again affects the scroll height.

To address this issue, there are some simple tricks you can implement. Adding padding-top: 50px; to the scrolling element and ensuring the header stays fixed will resolve the problem.

.App {
  padding-top: 50px;
}

.header {
  width: 100%;
  height: 50px;
  background-color: teal;
  position: fixed;
  top: 0;
}

.header-scrolled {
  width: 100%;
  height: 50px;
  background-color: green;
  color: white;
  position: fixed;
  top: 0;
}

https://codesandbox.io/s/lingering-pine-puunf

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

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

JavaScript function encountered an error due to an expected object

Currently, I am in the process of developing an application using VS2015, JavaScript, Angular, and MVC 5. Here is an excerpt of my JavaScript code: var myApp = angular.module('QuizApp', []); myApp.controller('QuizController', [&apos ...

Return an array that has been filtered to exclude any elements that are also found in a separate array

I have an API that provides a list of cars. const getAsset = async () => dbApi('list_cars', ['', 100]) .then(result => result.map(e => e.symbol)); Here, the function getAsset returns the car list. 0: "BMW" 1: "HONDA" 2: " ...

Utilizing retrieved information as properties in Next.js

After making some changes to my code, I encountered an error message stating 'Cannot destructure property 'id' of 'query' as it is undefined.' Can someone please explain why this error is occurring? Even though I have performe ...

Autonomous boundary for list elements

I have a specific issue that can be observed in this fiddle: http://jsfiddle.net/h0qu4ffv/ where I set the margin-top of one list item to 50px, but all list items end up following this style. Is there a way to give each list item an independent margin, or ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...

When a checkbox is within a container that contains images, it will trigger the event twice

I'm facing an issue with the Google map on my website. Whenever a marker is clicked, an infowindow opens with a checkbox that has a unique id. When this checkbox is checked, a console message is triggered. Below is the code snippet: function initiali ...

Utilize visuals to select premade designs

I am looking to enhance the user experience in selecting templates on Wordpress by integrating images for a visual preview. Instead of a traditional text-based dropdown menu, users would be able to see what the template looks like before choosing it. EDIT ...

I am attempting to send an array as parameters in an httpservice request, but the parameters are being evaluated as an empty array

Trying to upload multiple images involves converting the image into a base64 encoded string and storing its metadata with an array. The reference to the image path is stored in the database, so the functionality is written in the backend for insertion. Ho ...

Does JavaScript array filtering and mapping result in a comma between each entry in the array?

The code snippet above showcases a function that retrieves data from a JSON array and appends it onto a webpage inside table elements. //define a function to fetch process status and set icon URL function setServerProcessesServer1761() { var url = "Serv ...

JQuery Mobile fails to apply consistent styling to user input check items within a list

I have successfully implemented the functionality to add user input items to a checklist. However, I am facing an issue where the newly added items are not adhering to Jquery Mobile's styling. Here is a screenshot showcasing the problem: Below is th ...

Enclose Words Inside Unconventional Outline

Place text within a uniquely shaped border… I am attempting to achieve this goal in the most responsive and backward compatible way possible. I understand that compromise may be necessary. I have made progress with the help of this thread, but the svg ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

Exploring the world of AngularJS and delving into the

Lately, I've come across articles discussing Google's ability to now crawl websites and render CSS and Javascript. For example, Google themselves have talked about it in this article: My setup involves a single page application built with Angula ...

What steps should I follow to align these unordered lists side by side?

Is there a way to align these lists (unordered lists inside list items 1 through 4) side by side using CSS3? I've tried different methods, but I can't seem to figure it out. Here is the code I've been using: <footer> <ul> ...

Ways to modify the content of the "file" <Input> component in Ant Design

It seems pretty clear from the title. Despite checking the documentation and other sources, I am unable to change both the texts of the label: neither "Choose file," nor "No file chosen." Here is what I have attempted so far. How can I modify those text ...

Error: The value of _This.props is not defined

Hey there, I am new to working with React Native and could really use some assistance with this issue: TypeError: _props.goToScreen is not a function. Any help would be greatly appreciated, thank you in advance! In my Profile.js file, I am trying to click ...

Tips for Selecting the DIV Element using jQuery

I am faced with the challenge of integrating this particular set of div tags: <div id="target-share"> <a href="#" title="" id="to-chosen" class="default"><span class="to-admin">Admin</span></a> <ul id="select-shareto"> ...

Is there a glitch causing the Owl carousel to malfunction?

I am struggling to implement a fullwidth owl carousel slider on my webpage, but I'm facing issues with getting it to function properly. I suspect there might be a conflict with the current template that I'm using. Here is the step-by-step proce ...

List of random items:1. Red pen2

By using JavaScript, I want to generate a paragraph that contains a randomly ordered list of items (presented in paragraph format) for a basic website. The input would include: apples concrete a limited dose of contentment North Carolina The final ...