I am working with modules and JavaScript and I have a slight confusion that I'd like to get figured out.
I would simply like to display a message on to my screen. I have attached an event listener to the onload event in the body tag. When that function is called, it changes the textContent property of a label to "hello."
The JavaScript (index.js):
function documentLoaded() {
document.getElementById('label').textContent = 'hello';
}
The HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Testing Modules</title>
<meta charset = "utf-8">
</head>
<body onload='documentLoaded()'>
<pre id='label'></pre>
<script src='index.js'></script>
</body>
</html>
Now, let's say I wanted to include a module in my code to make my JavaScript files smaller. I realize that this would not be necessary in this case. My module will include a variable for the text that I want to display on the screen.
The module (module.js):
export const message = 'hello';
index.js:
import { message } from './module.js';
function documentLoaded() {
document.getElementById('label').textContent = message;
}
HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Testing Modules</title>
<meta charset = "utf-8">
</head>
<body onload='documentLoaded()'>
<pre id='label'></pre>
<script type='module' src='index.js'></script>
</body>
</html>
When I run this code, I am given an error: "Uncaught ReferenceError: documentLoaded is not defined at onload." When I remove the call to documentLoaded() at onload as well as change the text content outside of the function, like so:
The module (module.js):
export const message = 'hello';
index.js:
import { message } from './module.js';
document.getElementById('label').textContent = message;
HTML:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Testing Modules</title>
<meta charset = "utf-8">
</head>
<body>
<pre id='label'></pre>
<script type='module' src='index.js'></script>
</body>
</html>
The code runs successfully and I am able to change the text content of the label element to the message from the other module. I'm confused why my first approach did not work, however. Are event listeners, such as the function called at onload, not allowed to be used in a module, or is there something else that I'm missing?