I am trying ES6 module in google chrome. I would like to launch an alert() (in an imported function) when i click on the button.
js/notification.js is well loaded but when I click on the button I get an error:
Uncaught ReferenceError: createNotification is not defined at HTMLButtonElement.onclick ((index):24) <- line of the button in index.html
index.html
<head>
<script type="module" src="js/main.js"></script>
</head>
<body>
<section id="container">
<button type="error" onclick="createNotification()">Create</button>
</section>
</body>
js/main.js
import {createNotification} from './notification.js';
js/notification.js
export function createNotification(type){
alert();
}
Functions used in onxyz
-attribute-style handlers must be globals (it's one of the many reasons not to use them). Your function isn't a global, it's local to the module in which you're importing it. (Remember: Your main script is a module too; if it weren't, you couldn't use import
in it.)
You could make it a global by assigning to a window
property:
window.createNotification = createNotification;
but it would be much better to use modern event handling:
document.querySelector("#container button").addEventListener("click", createNotification);
Live example on plnkr, obviously will only work on cutting-edge browsers with module support.
Side note: As Andreas points out, type="error"
isn't valid for button
elements. Valid types are button
, submit
, or reset
, with submit
being the default. (I've changed it to button
in the plnkr.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With