1

I'm still a beginner in Nextjs, trying to implement a simple javascript like:

document.addEventListener("scroll", function () {console.log("scroll!")})

how to add the function in a local file and then load it with <script/> in nextjs ?

P.S: i made a .js file with the function inside inside the project folder and tried to load it with next Script component but it gives me this error: Failed to load resource: the server responded with a status of 404 (Not Found)

1
  • 1
    "404 Not Found" means exactly what it says... the resource was not found. This doesn't mean that the code you're showing is wrong in any way, it means that when the browser made the request to get that JavaScript file it wasn't where you expected it to be. We can't see anything about the URL(s) involved, how you're serving the application, where your files are located, etc. Commented Jun 21, 2022 at 18:41

1 Answer 1

2

Next.js works with Modulation system.

If you want to add this function in some file, you need to export this function.

The code of the external file, let's call it "externalFile.js"

export function addScrollEventListener() {
  document.addEventListener("scroll", function () {console.log("scroll!")})
}

Then when you want to use it in your component, you need to import it.

import { addScrollEventListener } from './externalFile';

In the useEffect hook ( which executes after mounting ), you can use it.

useEffect(() => { addScrollEventListener() }, [] )
Sign up to request clarification or add additional context in comments.

4 Comments

and if the external file is in any random folder in the project lets say its called "lib" will it work if i imported the right path ? like this: import { addScrollEventListener } from '../lib/externalFile';
'../lib/externalFile' , this will work if the "lib" folder is the sibling of the file's parent.
as "../" will back by path byone folder.
it worked, now things make a lot more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.