HTML:
<html>
<body>
<button onclick="bgTime()">CHANGE BACKGROUND</button>
</body>
<script type="text/javascript" src="script.js">
</script>
</html>
JavaScript:
function bgTime() {
var d = new Date();
if (d getHours() >= 21) {
document.body.style.backgroundImage = "url('bg/H.png')"
}
else if (d getHours() >= 18) {
document.body.style.backgroundImage = "url('bg/G.png')"
}
else if (d getHours() >= 15) {
document.body.style.backgroundImage = "url('bg/F.png')"
}
else if (d getHours() >= 12) {
document.body.style.backgroundImage = "url('bg/E.png')"
}
else if (d getHours() >= 9) {
document.body.style.backgroundImage = "url('bg/D.png')"
}
else if (d getHours() >= 6) {
document.body.style.backgroundImage = "url('bg/C.png')"
}
else if (d getHours() >= 3) {
document.body.style.backgroundImage = "url('bg/B.png')"
}
else {
document.body.style.backgroundImage = "url('bg/A.png')"
};
};
Okay so I am probably just being an idiot somehow, but I cannot find what I am doing wrong. I get two errors:
1. "script.js:3 | Uncaught SyntaxError: Unexpected identifier"
2. "(index):3 | onclick | Uncaught ReferenceError: bgTime is not defined "
Can someone please tell me what I am doing wrong? Thank you in advance!
P.S. This is just a project for learning JS, don't judge lol.
3 Answers 3
Write
d.getHours()
getHours is a method of d which is accessed using the dot ..
answered Apr 16, 2015 at 19:59
user1907906
Sign up to request clarification or add additional context in comments.
Comments
You forgot a period. It should be:
d.getHours() >= 21 et cetera. :)
answered Apr 16, 2015 at 19:59
Chris Brendel
7003 silver badges10 bronze badges
Comments
You need to use dot notation on all of your if statements:
if (d.getHours() >= 21) { ... }
bgTime is not defined because the JS interpreter can't decode your program. Once you fix your ifs, everything should work fine.
References:
answered Apr 16, 2015 at 19:59
Sumner Evans
9,2055 gold badges32 silver badges48 bronze badges
Comments
lang-js
d getHours(), notd.getHours()?