-2

I followed this to set up the node.js server: Using node.js as a simple web server

So I installed the serve-static npm.

I then created a file called file called test.html with the following code

<html>
<head>
  <h2>Google</h2>
</head>
<body>
  <button onclick="test()">Click me</button>
</body>
</html>

<script src="http://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript">

  function test() {
    console.log('test');
  }

</script>

When I click on the button, I get:

Uncaught ReferenceError: test is not defined
at HTMLButtonElement.onclick (test.html:8)

and nothing else. This code looks ok...? Why is this function not found?

Zonus
  • 2,313
  • 2
  • 26
  • 48
  • Not only that, but you have to separate your external JS and your local one. Load jQuery in a ` – Terry Aug 29 '18 at 18:48
  • Sorry, I'm new to JS. I'm not following you? – Zonus Aug 29 '18 at 18:50

3 Answers3

3

Remove your src part if you want to have your own function in between your script tags.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
  function test() {
    console.log('test');
  }
</script>

Also, you should put your scripts before your </body>

dziraf
  • 3,607
  • 1
  • 16
  • 22
1

Put your javascript just before closing body tag (</body>)

And in your case you are binding event handler in the html itself, in this case you have to define those functions before you use them.

In this case put test() function code in head tag. It will work fine

0

Your JavaScript (script tag) is outside of html element. Put it in head or body.

Axar
  • 521
  • 1
  • 3
  • 11