2

How do you call a function from a module JavaScript file from an onclick or normal JavaScript.

In the code below the button click throws a "exampleFunction is not defined" exception (testing with the latest FireFox version and looking to be compatible with modern browsers)

exampleModule.js

export function exampleFunction(){
    alert('example Function');
}

examplePage.html

<html>
    <head>
        <script src="exampleModule.js" type="module"></script>
    </head>
    <body>
        <button onclick="exampleFunction();">button</button>
    </body>
</html>
webwake
  • 1,154
  • 1
  • 13
  • 26
  • You need to import the script into the file before using it. – nircraft Jul 08 '20 at 20:05
  • just import the function here we have the same question https://stackoverflow.com/questions/49338193/how-to-use-code-from-script-with-type-module?answertab=votes#tab-top – iTox Jul 08 '20 at 20:05
  • And you need to assign the function to the global object (`window`) so you can use `exampleFunction();` from the attribute. You can also use `addEventListener()`. – D. Pardal Jul 08 '20 at 20:06
  • You will find here the answer --> https://stackoverflow.com/questions/49338193/how-to-use-code-from-script-with-type-module – Ivan Lynch Jul 08 '20 at 20:10

2 Answers2

2

you can register the onclick Handler inside the Module

var element = (get your element with any document.<> Method)
element.addEventListener("click" (e) =>{ /*Your Handler Function */})
1

Try to use this function in a global context, use window

exampleModule.js

exampleFuction=function(){
    alert('example Function');
}
export exampleFunction // export as a module
window.exampleFunction = exampleFunction; // export to the global context
F.Igor
  • 4,119
  • 1
  • 18
  • 26
  • For only something like an onclick that fills up your global variable Space and all modules are loaded Async so it could happen, that the "exampleFunction" is not defined when the user tries to click so there would be an error – Martin Scheuchenpflug Jul 08 '20 at 20:13