9

I have a simple HTML page, which is importing a JS module as follows:

.. snip
<button onclick="btnClick()">Go!</button>

<script type="module">
import { func1 } from './utils.js'

function btnClick() {
   func1()
}
</script>

Clicking the button produces an error: btnClick() is not defined.

Why is this happening? How to bring these functions back into correct scope?

1

3 Answers 3

8

The javascript execution stack has own scope, so, simple and easy solution is, you can assign to window scope your accessible functions like below;

<button onclick="btnClick()">Go!</button>

<script type="module">
    import { func1 } from './utils.js'

    function btnClick() {
      func1()
    }

    // variable function
    window.btnClick = btnClick;

    // or anonymous function
    window.btnClick = function(youCanSetParams){
      func1()
    }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

If you have multiple functions, do something like window._myFns = { btnClick, onLoad }
1

when the script is with module type it can only listen to events and you can not call to function from the html , so you can add an EventListener to the click event , check the id of the target element that call dispatch the event and then call to the function:

<script type="module">
    import { func1 } from './utils.js'
    window.addEventListener('click' , e=> {
        switch(e.target.id){
           case 'btnGo':
             btnClick();
             break;
        }
    })
    function btnClick() {
       func1()
    }
</script>

<html>
    <button id="btnGo">Go!</button>
</html>

Comments

0

Variable from "module" are not accessible from outside so use type="text/javascript" as

<script type="text/javascript">

function btnClick() {
   console.log('here')
}
</script>
<button onclick="btnClick()">Go!</button>

2 Comments

This answer provides a workaround, but not the actual answer to what the OP asked. Can you provide a reference for this?
You can only use import and export statements inside modules, not regular scripts -> developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.