Muszyn
Muszyn

Reputation: 43

Why there's error in onclick when i have "module" in script tag?

I have button with function and it looks like this :

<button onclick="myFunction()">Click</button>
<script type="module" src="main.js"></script>

And there's main.js file :

function myFunction(){
   console.log('Button has been clicked');
}

Without module type in script tag it works fine but when there's module type in it, console throws error:

Uncaught TypeError: window.myFunction is not a function at HTMLButtonElement.onclick

How to fix it to work fine with module?

Upvotes: 4

Views: 1628

Answers (1)

Quentin
Quentin

Reputation: 943981

Default scope in modules is the module and not global.

Attach event handlers using addEventListener in JavaScript instead of intrinsic event attributes in HTML.

Upvotes: 8

Related Questions