JS "Function is not defined"- <script> src problem?

Absolute beginner here. I have been using codesandbox to build some projects, but for the life of me I cannot figure out how to get my JS file to point to my HTML file. I have stripped it to the absolute essentials: no matter what, I get a “functionName is not defined” error message.

I have stripped it down to basics: my index.js file contains:
function newAlert() {
alert(‘hello!’)
};

I have tried putting the script src tags in the body, in the head, but nothing. Does it have to do with how I am defining my functions?

Are you sure you are using real single quotes in parentheses inside alert?
When I copy ‘alert(‘hello!’)’ from your post, those are not a valid single quotes.

It works fine with me, I just changed the quotes: https://i.imgur.com/wT6bDsu.png

Yes, I am pretty sure that is not the problem. When I call the function in the .js sheet it works fine. It’s only when I try calling it from the HTML that I get the “newAlert is not defined” error.
Screenshot 2022-01-27 2.42.23 PM

Yeah, I guessed it was just forum’s formatting… Anyway, everything looks ok with your code, you could just switch to some other platform, that is very strange. I even tried it at w3schools now and works too: https://i.imgur.com/3MS72lG.png

I want to say this is just a quirk of the build tool.

If you instead add the click event listener in your script, it works just fine.

  • Remove the onclick attribute on the button
  • Add document.querySelector('button').addEventListener('click', newAlert) to your script

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.