Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
How to run a JavaScript function on a html page having a specific element with Webpack?

In the client side, I have structured my code like this:

client
├── js
│   ├── sidebarTemplate.js
│   └── scrollToTop.js
├── _view
│   ├── index.html
│   └── a.html
│   ├── b.html
│   └── c.html
├── index.js

In details: I have multiple html files placed in view folder, different custom JavaScript functions placed in js folder, and the index.js file works as the entry point for webpack setup. The view folder has index.html, a.html, b.html, c.html files. The js folder has sidebarTemplate.js file which is used to populate the sidebar of all html pages in the view folder, and scrollToTop.js file which is used when user want to get back to the top for only the pages that have button element.

In index.js" file, I place my Js functions:

//add the side bar for all html files
addSidebarTemplate();
//Load the page having the button element 
//if user click the button then run the function to going to the top of the page
document.addEventListener('DOMContentLoaded', toTheTop);

The function to populate the sidebar elements for every pages and it works perfectly fine to any page that I clicked on. However, When I tried to run the function to scroll to the top for example the page c.html. It did not work. Looking at the console, for the c.html page, there was no errors shown off, but for index.html, a.html and b.html pages, the error was "Uncaught TypeError: Cannot read properties of null..."

I have tested my code by only working with c.html file, and toTheTop function by placing the in another folder and it worked. So, there's nothing wrong with my js functions.

My overall question is that How can I organize the index.js file so that when I call a function, the function only works for a specific html page not all of them. It would be great if you guys can give me some articles to fix the issue. Thank a lot!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!