I'm having trouble with my scroll bar in a React project using JavaScript. Can anyone spot what might be causing the issue?

Attempting to create a React site for the first time, so please forgive any novice mistakes or oversights on my part. Currently, my navigation bar is fixed at the top of the page with basic hover animations. I am aiming for it to disappear when scrolling down and reappear when scrolling up, similar to the effect demonstrated in this YouTube tutorial here.

Below is the current JavaScript code:

import React from 'react';
import './Header.css';

const body = document.body;
let lastScroll = 0;

window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;
  if (currentScroll <= 0) {
    body.classList.remove("scroll-up");
  }
  if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-up");
    body.classList.add("scroll-down");
  }
  if (currentScroll < lastScroll && body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-down");
    body.classList.add("scroll-up");
  }
  lastScroll = currentScroll;
});
const Header = () => {
  return (
    <header className="header">
      <div className="logo-container">
        <a href="https://github.com/avarga1"><i className="fab fa-github"></i></a>
        <a href="https://www.linkedin.com/in/austin-varga-2611b9259/"><i className="fab fa-linkedin"></i></a>
        <a href="#home"><i className="fab fa-youtube"></i></a>
        <a href="https://twitter.com/"><i className="fab fa-twitter"></i></a>
      </div>
       <nav>
        <ul>
          <li><a href="#home" className="nav-link">Home</a></li>
          <li><a href="#home" className="nav-link">About</a></li>
          <li><a href="#home" className="nav-link">Projects</a></li>
          <li><a href="#home" className="nav-link">Contact</a></li>
        </ul>
      </nav>
    </header>
  );
}

export default Header;

Here's the accompanying CSS:

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgb(85, 85, 85);
  opacity: 0.85;
  color: white;
  font-size: 24px;
  position: fixed;
  top: 0;
  z-index: 9999;
 width: 100%;
}
... // rest of CSS properties

/*   Scroll      */
.scroll-down header {
  transform: translate3d(0, -100%, 0);
}

.scroll-up header {
  transform: translate3d(0, 0, 0);
}

Additionally, here's the App.js file:

import React from 'react';
import './App.css';
import Header from './Header.js';
import Contact from './Contact.js';
import Landing from './Landing.js';
import Sidebar from './Sidebar.js';
import Main from './Main.jsx';


function App() {
  return (
    <div>  
        <Header/>
        <Main />
        <Sidebar />
        <Landing />
        <Contact />
    </div>
  );
}

export default App;

If anyone has insight on how to achieve the desired behavior, it would be greatly appreciated!

Answer №1

If the condition for a check in the code has been fulfilled, it is advised to exit the execution from that specific if-condition block.

window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;

  if (currentScroll <= 0) {
    body.classList.remove("scroll-up");
    return; // Alternatively, return with a value or set lastScroll = currentScroll before this empty return;
  }
   
  if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-up");
    body.classList.add("scroll-down");
    return; // Alternatively, return with a value or set lastScroll = currentScroll before this empty return;
  }

  if (currentScroll < lastScroll && body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-down");
    body.classList.add("scroll-up");
    return; // Alternatively, return with a value or set lastScroll = currentScroll before this empty return;
  }


  
  lastScroll = currentScroll;
  
});

An important aspect to consider is how and where the scroll-up and scroll-down functionalities are attached. The placement of the Header component within the DOM structure of the body plays a significant role. The code verifies in

body.classList.contains("scroll-down")
, but ideally should confirm if the class name is applied to the parent div of the Header component?

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

Steps for generating an HTML form in a fresh window

I am currently working with this function: // open a new window. Create and submit form function createSubmitForm(response) { var external = window.open('about:blank', 'external'); var doc = external.document; var body = $( ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...

Converting a ReactJS input element from controlled to uncontrolled while maintaining a specified value state

The section of my code that is causing issues appears as follows: const normalizeInput = (value, previousValue) => { if (!value) return value; const currentValue = value.replace(/[^\d]/g, ''); const cvLength = currentValue.le ...

My custom font is not compatible with the browser on my asp.net site

I'm having trouble embedding my own font in my .aspx file. Google Chrome and Firefox don't seem to support the font, while IE does. Can someone please provide guidance on how to successfully embed the font in an asp.net page? Below is my code: ...

An error has occurred with the Firefox Addon: the module `path` cannot be located within the resource://gre/modules/commonjs/http.js

Currently developing a Firefox add-on on Windows10 with node v5.8.0 and npm v3.5.3, using Firefox v.45.0 The issue arises from the following line of code: var path = require("path"); The error message reads: Message: Module `http` is not found at resou ...

It is not possible to adjust the audio volume using the useRef hook

I keep encountering an error that says The left-hand side of an assignment expression may not be an optional property access whenever I try to adjust the volume of the htmlaudioelement Does anyone have any suggestions on how to resolve this issue? Here i ...

Production environment poses a challenge as Rails 4 struggles to locate fonts

Situation: I am facing an issue with my Rails 4.0.0 application deployed using capistrano, where the asset precompilation does not work properly on my production server. Challenge: Despite successfully adding a font and using it with @font-face locally, t ...

What's the best way to fill checkboxes in EJS when editing a route?

As a beginner, I am working on my first project - a simple content/property listings app. I have created a form to collect user data and display it on a show form. The form includes sections for checkboxes and radio buttons, with the values being stored i ...

Even with employing Cors alongside Axios, I continue to encounter the following issue: The requested resource does not have the 'Access-Control-Allow-Origin' header

When working with a MEAN stack app, I had no issues with CORS. However, upon transitioning to the MERN stack, I encountered an error related to CORS despite having it implemented in the backend: Access to XMLHttpRequest at 'http://localhost:5000/api/ ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

What is the best way to receive a callback when a user cancels a dialog box to choose a mobile app after clicking on

I am currently exploring HTML coding for mobile devices and looking to integrate map routing functionality. When it comes to mobile devices, utilizing the local app is the more practical option, and I have had success implementing this by modifying the l ...

Is it common for content to duplicate when using the 'position: fixed' property in CSS media print?

Consider the following div element: ... <div id='section-to-print'>CONT /*Content*/ </div> ... Accompanied by this CSS code snippet: @media print { * { -webkit-transition: none !important; ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

Jade fails to show image in route with parameter

Currently, I am utilizing express 4 and have images saved in the uploads directory. This is a snippet of my code: app.use(express.static(__dirname + '/uploads')); //This part works app.route('/') .get(function (req, res) { ...

The Autocomplete feature in Material UI is failing to function properly when paired with a

I have a requirement to customize the Autocomplete Highlight feature provided in a specific example to suit my project needs. (Link: Material UI Autocomplete Documentation) The original Highlight example includes borders which I removed by referring to th ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

Step-by-step guide on retrieving the button text by utilizing a method call

Currently, I am troubleshooting a demo and I'm puzzled as to why the text of the #add-point button is not displaying. $("#add-point").on("click", function(){ activatePointTool(); }); function activatePointTool() { var tool = $(this).text().toU ...

What causes the component to remount with every update to its state?

PLEASE NOTE: Before posting this question, I realized that there were some errors in my code. I understand now that this question may not be helpful to others as it contains misleading information. I apologize and appreciate those who took the time to res ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Error: Unable to locate module adaptivecards-templating

After adding the module through the command: npm install adaptive-expressions adaptivecards-templating --save and importing it, I encountered an error when trying to run my application: ...