Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function from JavaScript module in HTML

Say, I have the following JavaScript module using Vue:

import Vue from "./vue/vue.esm.browser.js";

const app = new Vue({
    el: '#app',
    data: {
        message: 'Hello, world!',
    }
});

// Custom function for calling by the button
function changeMessage() {
    app.message = 'Hello from button!';
}

Now I refer to this module:

<script src="js/site.js" type="module"></script>

Then I try to call changeMessage:

<button onclick="changeMessage();">Press me</button>

However, I get the following error in console:

Uncaught ReferenceError: changeMessage is not defined at HTMLButtonElement.onclick

Moreover, in Visual Studio I don't even get it in IntelliSense. When I remove type="module", then everything works fine. How to make html see the module functions?

like image 486
JohnyL Avatar asked Mar 16 '26 10:03

JohnyL


1 Answers

You can define the function on the global window object:

<script type="module">

  window.greet = function () {
    alert('Hello')
  }

</script>

<button onclick="greet()">Hello</button>
like image 166
Decade Moon Avatar answered Mar 19 '26 00:03

Decade Moon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!