Tell us what’s happening:
Describe your issue in detail here.
I am trying to do something similar in personal project by adding a button and a function being invoked on onclick from js file, importing this function from another js file. “Uncaught ReferenceError: monit is not defined” is all I am getting after clicking the button. How is it supposed to be done correctly?
I’m not totally sure why, but when you use script type module, you have to expose variables to the global window object: window.monit = monit. I know this is not best practice, though.
The function monit isn’t defined anywhere – in the code you posted it’s commented out, so naturally you will get an error saying that it isn’t defined. If it is defined in a different file you actually need to import the function, JavaScript can’t magically know it’s there. edit, sorry, misread code (cheers @ochsec )
Also, minor, but you use eitherasync or defer on a script tag in HTML. But those attributes are for scripts that aren’t of type “module”. As you’ve said the type is “module” that’s already async so neither of the attributes are needed.
Don’t use the onclick attribute @6977wojtek1978, add an event listener, the function is not in the global scope (or add it to the global scope as @jonathan.roley suggests, but using an event listener is IMO and IME more sensible).
Following works fine (I’ve elided anything not relating to the code being used):
Note it must be run on a server over HTTP, you can’t just open the HTML file in the browser, JS modules will not work against file:// URLs. So for example, I set up the files like this:
monit
├ index.html
├ js.js
└ math_functions.js
Then I cded into monit and (given Node is installed), ran npx servor . (ie I just ran a program that runs a server, this one happens to be a server called “servør”), server runs on localhost, so I get this:
the attribute value is literally the JavaScript code you want to run when the event occurs.
The function is not used as a callback, it must be invoked (). That is when onclick fires it runs the code and monit is just an identifier that contains the function definition so running that code does nothing.
Thank you! Looks like I wasn’t running this thing on the server over HTTP, that was the main reason it wasn’t working. Thank you people, especially @DanCouper!