9

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();
}
artless boy
  • 431
  • 1
  • 5
  • 11
  • Which Chrome version you are using? – HimanshuArora9419 Jan 31 '18 at 06:33
  • 1
    `error` is not a valid type for a ` – Andreas Jan 31 '18 at 06:34
  • 63 (module should work since 61) and type is just for css, not sure it s good or not! – artless boy Jan 31 '18 at 06:50
  • @artlessboy: It's not, it's invalid. :-) Instead, change the CSS to use a class and put that on the button instead (and then leave off `type` if you want a submit button, or change it to `"button"` if you want a non-submit button). – T.J. Crowder Jan 31 '18 at 07:05

1 Answers1

13

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875