Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event.
I am working with nextJS 13 and tailwind css.

const [shadow, setShadow] = useState(false);

useEffect(() => {
  const handleShadow = () => {
    if (window.scrollY >= 90) {
      setShadow(true);
    } else {
      setShadow(false);
    }
    window.addEventListener("scroll", handleShadow, true);
  };
  return window.removeEventListener("scroll", handleShadow);
}, []);

inside my HTML element

<div
  className={
    shadow
      ? "fixed left-0 top-0 w-full z-10 ease-in duration-300 bg-[#112240] shadow-xl"
      : "fixed left-0 top-0 w-full z-10 ease-in duration-300 bg-[#112240]"
  }
>
other code
</div>

Answer №1

The error in your code is caused by the event listener being initialized within the handleShadow function. By relocating it outside of the function, you can resolve this issue.

const [shadow, setShadow] = useState(false);

useEffect(() => {
  const handleShadow = () => {
    if (window.scrollY >= 90) {
      setShadow(true);
    } else {
      setShadow(false);
    }
  };
  window.addEventListener("scroll", handleShadow, true); //moved it out the function's body
  return window.removeEventListener("scroll", handleShadow);
}, []);

Answer №2

Give this a shot

try {
  const handleScroll = () => {
    if (window.scrollY >= 90) {
      setScrollActive(true);
    } else {
      setScrollActive(false);
    }
  };
  window.addEventListener("scroll", handleScroll);
} catch(err) {
  console.error("An error occurred while handling scroll:", err);
}

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

Rampant number of objects contained within box element

I am currently working on a box component that contains flex items. Unfortunately, I am facing an issue where the box width remains constant and causes overflow when I try to reduce its size in order to accommodate all the items. Can anyone provide guidanc ...

Displaying checkbox values with JavaScript

How can I display multiple checkbox values when checked in HTML code? Whenever I check a checkbox, I want its value to be shown alongside the previously checked values. Right now, my code only displays one value at a time. Any suggestions on how to achie ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

Invoke PHP by clicking on a button

I am facing an issue with a button I have created. Here is the code for it: <input type="submit" name="kudos_button" value="★ Give kudos"/>' To test it, I wrote a PHP script like this below the </html> tag: ...

Challenges with character encoding in NextJS

I am currently dealing with a line of code that creates a dynamic route. <Link href={`/bundeslander/${urlName}`} ><div className=" text-blue-400">{state.name}</div></Link> The variable urlName is generated by fetching dat ...

Troubles with submitting jQuery validation plugin via AJAX

Whenever I try to use the jQuery validation plugin for validating a form within a Bootstrap modal, the validation does not work and the form cannot be submitted. This is the code for the Bootstrap modal form: <div class="modal fade" id="form-content" ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Efficiently processing multiple Ajax requests with a single callback function

I am currently facing a situation where I need to make multiple AJAX requests and only proceed if all of them are successful. The typical usage of $.when($.ajax(), [...]).then(function(results){},[...]); doesn't quite fit my needs because the number o ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

What is the extent of an object within a JavaScript Array?

Exploring scopes in JavaScript has led me to an interesting discovery when calling functions from an array. In the example below, I experiment with three different scopes: one bound to an Object named foobar, one bound to window, and a third one which po ...

Issue: The build process for a Next.js app is encountering an error due to the lack of a module factory for the dependency type CssDependency. This is

After running npm run build in my nextjs project, I encountered the following error: Error: No module factory available for dependency type: CssDependency A build error occurred: Error: > Build failed because of webpack errors at build (D:\proje ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

Background PHP/JS authentication through HTTP

Recently, I developed a PHP website that includes embedded web-cam snapshots which refresh every 2 seconds using JavaScript. For the first camera, I can easily log in using URL parameters like this: cam1-url?usr=usr&pwd=pwd. However, the second camer ...

Guide on making API calls in AngularJS using query strings

I am new to learning about AngularJS and recently came across a helpful article on connecting to an API and using its data in our app. The article specifically focuses on displaying weather information with AngularJS. The only downside is that the weather ...

Is there a CSS alternative to using <br clear=all> on divs that do not have set heights?

Back in the day, I used to rely on <br clear=all> at the end of a div, without specifying a height value in CSS, just to control its height. These divs would expand and contract based on the content within. Is there a more elegant approach to make ...

Understanding the Issue: Why Doesn't Signing Up with an Existing Account Automatically Log In When Using the 'autoconfirm' Feature in Supabase Authentication?

When using the supabase.auth.signUp function in my code, I expected a logged-in session with "autoconfirm" enabled on the server. However, after signing up with an existing account, it didn't log me in as anticipated. Here's a snippet of the code ...

Retrieve all visible rows using the AngularJS UI-scroll feature

As of now, I have integrated angular-ui/ui-scroll to dynamically load items into a table. Is there a method available to retrieve the visible items that are currently being rendered on the UI using ui-scroll? I have been utilizing adapter.topVisible and ...

When the state changes in React, the useSelector hook does not provide real-time updates

Currently, I am in the process of implementing a search feature using React and Redux Thunk. The main requirement for this search functionality is to fetch data from an API by calling a thunk action and updating the state accordingly for display on the UI. ...

Tips for avoiding parent div click interference in Angular

Working with Angular8, I have a div containing a routelink along with other components including a checkbox. Here's the structure: <div [routerLink]="['/somewhere', blablabla]"> <!--other components that navigate to the ro ...

How can I activate the socket.io connection event in NodeJS?

I'm currently experimenting with socket.io on NodeJS and I am facing a challenge in figuring out how to activate the socket solely from NodeJS. Previously, I have been using socket.io by invoking it from the front end. However, I am curious if it is ...