0

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.

asked Apr 16, 2015 at 19:56
3
  • 5
    Is it really d getHours(), not d.getHours()? Commented Apr 16, 2015 at 19:57
  • I knew I was just being dumb haha thank you! Commented Apr 16, 2015 at 19:59
  • 1
    The first error occurs, indicating a problem in the loaded JavaScript; with the issue in that code, the function is not "created" and made available for when you click, hence the second error. Commented Apr 16, 2015 at 20:02

3 Answers 3

2

Write

d.getHours()

getHours is a method of d which is accessed using the dot ..

answered Apr 16, 2015 at 19:59
Sign up to request clarification or add additional context in comments.

Comments

1

You forgot a period. It should be: d.getHours() >= 21 et cetera. :)

answered Apr 16, 2015 at 19:59

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.