3

<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

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
Rkcoder
  • 31
  • 5

4 Answers4

4

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>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

This is what your script should look like:

<script>
  function sayHello(){  
    console.log('hello')
  }
</script>
Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
0

<button onclick="hellosay()">Click</button>
<script type="module">
  window.hellosay=()=>{
  console.log("hello")
  }
</script>
Rkcoder
  • 31
  • 5
0

For javascript modules create a .js or .mjs file and export your javascript functions

Mymodule.js

export function sayHell(){
    console.log("ok");
}

and import it.

Samples here https://github.com/mdn/js-examples/tree/master/modules/basic-modules

Documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Biju Kalanjoor
  • 532
  • 1
  • 6
  • 12