Troubleshooting Parallax Logic in NextJS

    import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Image from 'next/image'
import React, { useRef ,useEffect, useState } from 'react';

export default function Home() {
  let ref = useRef()
  const [offset, setOffset] = useState();
  
  useEffect(() => {
    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, []);
  
 
  return (
    <div className={styles.container}>
      <div className={styles.section}>

      <Head>
        <title>Parallax Effect</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Image className={styles.bg}
        src="/../public/bg.jpg"
        layout="fill"
        quality={100}
        />
      <Image className={styles.moon}
        src="/../public/moon.png"
        layout="fill"
        quality={100}
        // style={{ transform: `translateY(${offset * 0.5}px)` }}
      />
      <Image className={styles.mountain}
        src="/../public/mountain.png"
        layout="fill"
        quality={100}
      />
      <Image className={styles.road}
        src="/../public/road.png"
        layout="fill"
        quality={100}
      />

      <h2 className={styles.text}>Moon Light</h2>

      </div>
    </div>
  )
}

I am looking for assistance with the code above to achieve a parallax effect on scroll. I want the moon image to move left by 10px every time the user scrolls to the bottom.

  1. I aim to shift the moon image to the left by 10px upon scrolling to the bottom of the page.
  2. I want the h2 header to scroll under the road image as the user scrolls.
  3. The sky and mountain images should remain static while the moon and header respond to the scroll event listener.

Answer №1

To achieve a parallax effect without relying on external parallax packages, the first step is to import

useEffect from React: (the line below is necessary)

import React, { useEffect } from 'react';

In NextJS, in order to manipulate each image individually, you need to assign an id to each of them. For instance:

<Image className={styles.bg}
    id="bg"
    src="/../public/bg.jpg"
    layout="fill"
    quality={100}
    />

After assigning an id to each Image component, create a variable and select it like this:

var bg = document.querySelector('#bg');

Remember to place the above initialized variable into a function outside the return statement in your main function.

Now, to adjust the position of each selected variable which corresponds to your Image component, use the following code:

 bg.style.transform = `translateX(${window.scrollX / 2}px)`; 

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

Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to ach ...

Modifying a Nested Component with react-icons

As I work on creating a rating component that utilizes react-icons to display icons, I have encountered an interesting challenge. Currently, I am using the FaStarhalf icon which represents a pre-filled half star that can be flipped to give the appearance o ...

The URL routing in Vue-router seems to be incorrect as it directs to the wrong page. To fix this issue, make sure to include a '#' before the

Welcome to my website! Check out my home page here: https://i.sstatic.net/znfq0.jpg If you're interested in reading my blog, visit the blog page here: https://i.sstatic.net/oiYSY.png I've built this site using vue3. Here's a snippet of th ...

JavaScript (specifically, using jQuery) in conjunction with AJAX

After using validation with jQuery in JavaScript and applying it to ASP.NET controls within an AJAX update panel, I encountered a problem. The validations are working correctly, but the event of the button control is still being executed despite the valida ...

"Encountering issues with react-swipable-views when attempting to use it

I'm currently working on implementing react-swipable-views into my React application, but I encountered a specific error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite component ...

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

The ng-isolate-scope is not properly connected to the specified templateUrl

I am encountering difficulties when trying to implement isolated scope with templateUrl. Here is my directive test: beforeEach(ngModule('app.directives')); var scope, compile beforeEach(inject(function($rootScope, $compile){ scope = $ro ...

Express session not persisting following JQuery Get request

I need to save the server variable that the user inputs. Once they submit, they are directed to another page. On this new page, I check if their server exists and redirect them back if it doesn't. When I make a post request, the session is saved, and ...

Inexperienced JavaScript user looking for help with handling XMLHttpRequest response data

It's been well over a decade since I last dabbled in JavaScript, so here I am again. My goal is to create a dynamic graph that updates in real time using data from either my backend database or my ESP32 micro-controller. While it's easy to genera ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

I am looking for a specific task to be carried out, without any need for returning a value or any additional items

I am trying to remove an element from the canvas using Selenium. The command I am currently using is "window.app.design.internalLayer().find('.deletebutton').fire('click')". Despite my efforts, this command does not seem to be working a ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

Toggle on and off using a checkbox feature in conjunction with the straightforward form gem

Seeking assistance in toggling an action using a checkbox on a post form. Not well-versed in javascript or JQuery. Struggling with this task while working alone. If anyone can provide guidance, it would be greatly appreciated! Using Rails 4.2.8 an ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Pressing the enter key in an AngularJS form does not trigger submission

Having trouble with a login form that won't submit when the user presses enter. While the form works fine when the "Login" button is clicked, hitting enter doesn't trigger submission and leads to some unexpected behavior: The ng-submit associat ...