Can't call function from bodyload (uncaught reference error: start undefined) javascript
I have an onload body calling a function in javascript. I've tried a lot of things, but the console just prints in the error log: error uncaught reference: start is undefined. I think it may be a problem, please let me know if it works for you. My code looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Monster Invasion</title>
<script type="javascript">
var hur;
var monsters = 10;
var objective = false;
var health = 100;
var damage = 30;
var sheild = false;
var ea = 1;
function start() {
setTimeout(hurt,4000)
}
function hurt() {
var newhelth = health - damage;
health = newhelth;
document.getElementById("healtw").innerHTML = health;
start();
}
function kill() {
if(monsters > 0) {
monsters--;
document.getElementById("monster1").src="dead.jpg"
setTimeout(next,2000)
}else {
objective = true;
document.location="endoflevel.html";
}
}
function next() {
document.getElementById("monster1").src="monster.jpg"
}
}
</script>
</head>
<body onload="start()">
<p id="healtw"></p>
<embed src="guide_first_level.mp3" type="audio/mp3" hidden="true" autostart="true">
<a id="st" onclick="kill()"><img id="monster1" src="monster.jpg"></a>
<p id="ada"></p>
<a href="sheild.html">Activate sheild</a>
</body>
</html>
source to share
wrong script type
try it
<script type="text/javascript">
</script>
But you don't need to specify the script type
just use normal script tag
like this
<script>
</script>
One more thing to add is that before the script tag you add additional ones }
.
just remove it
function next() {
document.getElementById("monster1").src="monster.jpg"
}
} // <-- just remove this bracket
</script>
source to share
There are two problems with your code.
javascript is not a valid script type in the browser. Browsers know
text/javascript
, but not only javascript , so your code is not executed. Change the type attribute or remove it altogether (this is the default for TG41).You have an extra parenthesis} at the end of your code. Remove it and your code will work fine.
source to share
There are 3 errors:
- Correct the
type
script tag - At the end of the code there is an additional
}
- Instead of using the
onload()
for tag, it 'sbody
better to use itwindow.onload
like this to make sure your functionstart()
runs after the document is ready:
...
<head>
<title>Monster Invasion</title>
<script type="text/javascript">
window.onload = function(){
// Put all your code here
// And at the end run start() function
start();
}
</script>
</head>
<body>
...
source to share