How do you call a function from another javascript file with the type="module"

Viewed 701

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>
2 Answers

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 */})

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
Related