1

HTML:

<body>
  <script type="module" src="./script.js"></script>
  <div>Welcome to my first html page...</div>
  <div id="username">Another div tag</div>
  <p>This is a paragraph</p>
  <h1>Working on JS</h1>
  <button onclick="firstFunction()">Click</button>    
</body>

J/S:

function firstFunction() {
  console.log("Hurry")
}        

Getting error:

Uncaught ReferenceError: firstFunction is not defined

    at HTMLButtonElement.onclick (index.html:17)

onclick @ index.html:17

What might be the cause of this error?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • if I recall ... modules don't add to the global object - try `globalThis.firstFunction = function() { console.log("Hurry") }` – Jaromanda X Jul 16 '22 at 06:29

1 Answers1

0

Don't import the js script as module. use the following code instead :

<script src="./script.js"></script> `
Sanath.usk
  • 84
  • 5
  • what if they need it to be a module? then what? – Jaromanda X Jul 16 '22 at 06:35
  • @Sanath.usk then imports will not work in my js script, if I don't do module – zada sellers Jul 16 '22 at 07:16
  • @jaromanda-x if you need to use it as a module, firstly expose the firstFunction inside the script.js module by adding export modified as shown below: `export firstFunction() {...}` functions imported through module type are imported into the scope of a single script and aren't available in the global scope. Hence for it to work you will have to add it as property to window object: ``` lang-js ``` – Sanath.usk Jul 24 '22 at 07:08