So I'm trying to serve a simple web page. In my html I have a form and I'd like to simply say no results found when anything is searched for. If I place a javascript function into script tags into the html document the div gets populated. However whenever I use an external js file it isn't even executed. The console logs nothing and no alerts show up. The server is serving up these files however because if I log the request URL I see that /button_click.js is being served. Can someone explain why this happens? Here is my code for reference:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
body{background: skyblue; font-family: verdana; color: #fff; padding: 30px;}
h1{font-size: 48px; text-transform: uppercase; letter-spacing: 2px; text-align:center;}
p{font-size: 16px; text-align:center;}
</style>
<script type="text/javascript" src="button_click.js">
// if uncommented and without the src tag this seems to do the job
// function buttonClick() {
// document.getElementById('result').innerHTML = "No results found";
// return false;
// }
</script>
</head>
<body>
<h1> Welcome to the home page</h1>
<form id="form" onsubmit="return buttonClick()">
<input type="text" name="search"> <br>
<input type="submit" name="submit"> <br>
</form>
<p id = "result">
</p>
</body>
</html>
button_click.js
function buttonClick() {
console.log('in here');
alert("in here");
document.getElementById('result').innerHTML = "No results found";
return false;
}
UPDATE
My console gives me an unexpected token for "<" error at line 1 in my js file. When I do try and check the file through the browsers resources the js file is apparently exactly the same as my index.html file. It contains no javascript and has the contents of index.html. Why is this?
All my files are in the same directory and I have checked all the file names as well.Here are the contents of my server file for reference:
server.js
const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res) {
res.writeHeader(200, {"Content_Type": "text/html"});
var readStream = fs.createReadStream(__dirname + '/index.html', 'utf8');
readStream.pipe(res);
console.log(req.url);
console.log('served page');
});
server.listen(3000, '127.0.0.1');
console.log('Listening in port 3000');
document.onload();and test if it works. Or put your script tag before</body>tag