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!