Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function from javascript module in html onclick [duplicate]

<h1 onclick="sayhello()"> Hello Word</h1>

<script type="module" >
        sayhello=()=>{
            console.log('Hello');
        }
</script>

result is: (index):14 Uncaught ReferenceError: sayhello is not defined at (index):14

like image 463
Rkcoder Avatar asked Jun 08 '26 00:06

Rkcoder


2 Answers

You should either remove type=module:

<h1 onclick="sayhello()">Click</h1>
<script  >
    sayhello=()=>{
        console.log('Hello');
    }
</script>

Or attach the function to window to use it globally:

<h1 onclick="sayhello()">Click</h1>
<script type="module">
    window.sayhello=()=>{
        console.log('Hello');
    }
</script>
like image 186
Majed Badawi Avatar answered Jun 10 '26 15:06

Majed Badawi


<button onclick="hellosay()">Click</button>
<script type="module">
  window.hellosay=()=>{
  console.log("hello")
  }
</script>
like image 20
Rkcoder Avatar answered Jun 10 '26 14:06

Rkcoder



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!