From research, I have found that the two main methods to use on click events from modules are either to use global variables via the window object or to use query Selectors from within the javascript module. Here is a much reduced and simplified version of the code I am working on:
index.html
<div id="list">
<p id="text">Random Text</p>
<ul>
<li onclick="replaceText('Option A')">Option A</li>
<li onclick="replaceText('Option B')">Option B</li>
</ul>
</div>
<button onclick="replaceList()""> <h1>Press me</h1>
user_interaction.js
import { functionB, functionA } from "./functions.js";
export function replaceText(name) {
let currentText = "";
currentText = name;
document.getElementById("text").innerHTML = name;
}
export function replaceList() {
if (currentText === "Option A") {
document.getElementById("list").innerHTML = functionA("Option A");
}
if (currentText === "Option B") {
document.getElementById("list").innerHTML = functionA("Option B");
}
}
The issue I am facing is that: I need to import function A and function B from a separate file, but to do this - I must first convert my user interaction file into a module. But, by converting my code into a module - this causes the on click events to return
"Uncaught ReferenceError function is not defined at HTMLButtonElement.onclick"
when I try to import from user interaction. From research, I can tell that this is because imports from modules have their own scope and thus the function is not defined.
I would like to solve this issue with a method that does not use a query selector or a global function as I have been told that global functions are not best practice. The reason I would prefer to not use a query selector is that I would like (if possible) to see that there is an on click event handler on the tags instead of having no indicator in the html tag.
Just in case, I'd like to clarify a few things. I am aware of the two methods described in these links, however, I am asking whether it's possible to approach the issue from a different route - one that preferably keeps on click in the html tags without resorting to global functions or query selectors in javascript. Additionally, I would like to clarify that this code has been dramatically simplified so that I can clearly focus on the concept of the question.
Here are some sources from which I have conducted my research:
Unfortunately stackoverflow keeps viewing the links as improperly formatted code so will have to write them in a code block:
Random Text