Javascript button onclick event not triggered

I have a javascript file "functions.js" with the following:

function changeLabel() {
    alert("True");
}

a main javascript file server.js

var http = require('http');
var fs = require('fs');
var port = process.env.PORT || 1337;

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function (request, response) {
        response.writeHeader(200, { "Content-Type": "text/html" });
        response.write(html);
        response.end();
    }).listen(port);
});

and a html file with this:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <title>Welcome</title>
    <script type = "text/javascript" src="functions.js"></script>
</head>
<body>
    <button id="button" onclick="changeLabel()">Click me</button>
</body>

</html>

and my json is

{
  "name": "test",
  "version": "0.0.0",
  "description": "test",
  "main": "server.js",
  "author": {
    "name": ""
  }
}

When looking at the network tab i have this:
enter image description here

But I do not manage to get the alert when clicking the button. I am pretty new to javascript coding…
Do I need to include my functions.js in the json file?

I am using visual studio 2019.

Thanks for your help guys

1 thought on “Javascript button onclick event not triggered”

  1. Please check again, it already works. The reason it might not work is because you are using a http server. You are not serving the functions.js as a public or static file. So, the browser cannot find your JavaScript file.

    The alert correctly displaces onclick. You do not need to add anything in the package.json. The json file is only for any npm packages or dependencies that need to be installed before the code can be tested and run.

    Reply

Leave a Comment