Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript functions inside a <script type="module"> from HTML element events?

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?

like image 563
Ryan Griggs Avatar asked Jan 11 '20 06:01

Ryan Griggs


People also ask

How can a function be called from a script in JavaScript?

Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How is a module created in JavaScript and referenced in HTML?

Modules are independent and self-contained chunks of code. You create them by splitting up a larger program into logical parts or dependencies. Modules should be independent, specialized, and reusable. You use the import and export keywords to interchange functionalities between modules in JavaScript.

What is script type module in HTML?

A script tag having type="module" attribute specifies that it to be considered as a Javascript module. It may be importing other Javascript module(s) inside it and becomes a "top-level" module for the imported modules.


2 Answers

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>
like image 102
Phd. Burak Öztürk Avatar answered Oct 01 '22 16:10

Phd. Burak Öztürk


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>
like image 30
Shivaji Mutkule Avatar answered Oct 01 '22 16:10

Shivaji Mutkule