Reputation: 57
I'm starting with Express and I have already a problem in my first program. Below is the code I'm using. Layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(type='type/javascript', src='./public/javascripts/temperature.js')
index.jade:
extends layout
block content
h1= title
p Welcome to #{title}
input#textBox(type='text', name='textBox')
input#myButton(type='button', value='Random Temperature!', name='myButton', onclick='click()')
temperature.js:
const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
function click(){
var rnd = Math.floor(Math.random() * 100);
textBox.value = rnd;
};
When I run the application I'm able to see in the browser the text box and the button but when I click on the button nothing happens. I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?
Upvotes: 0
Views: 367
Reputation: 8243
1 and 2. Change:
script(type='type/javascript', src='./public/javascripts/temperature.js')
to
script(type='type/javascript', src='/javascripts/temperature.js')
since ./
for relative path, and /
is for root path + you shouldn't include public
in path.
js
file in public folder and served public folder
as static folder
in express with: app.use(express.static(__dirname + '/public'))
Also there is couple more issues:
change document.getElementById('tb')
to document.getElementById('textBox')
change script(type='type/javascript', ...)
to script(type='text/javascript', ...)
change onclick='click()'
to onclick='onclicked()'
and function click(){
to function onclicked(){
because i think click is reserved keyword in JavaScript.
rename Layout.jade
to layout.jade
since you extend layout
not Layout
Here is the project.
You can see the project here: https://codesandbox.io/s/nodejs-jade-js-kq945
(note that in this project,the index.js is in src folder, so static folder is path.join(__dirname, "../public")
, not path.join(__dirname, "/public")
. also you can run it online, fork it to edit it online, or download it from file -> export to zip.)
first i checked the network tab, it didn't load js file. (there wasnt any error, actually there wasn't any request to get js file)
i hit cntrl+u to check source code, and clicked on .js link, and it get me error '404 not found', so i found address is wrong, and i found out i should changed '/public/js/...' to '/js/...'.
even now, there isn't any request for js file in network tab, so i changed : <script type='type/javascript'
to <script type='text/javascript'
now js file is loaded in network tab, but the click function didn't work. i wrote click
in console tab, and it gives me the function. so the click
function is defined, but onlick='click()'
not works. after some minutes, i guessed its problem with click
word, so i renamed it.
Upvotes: 1