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

Viewed 1061

<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

4 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>

This is what your script should look like:

<script>
  function sayHello(){  
    console.log('hello')
  }
</script>

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

Related