Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem with your third (non-working) bit of code is that you are trying to change the source attribute of an element that doesn't exist when the script is run. Generally speaking the browser parses the page's HTML from top to bottom, when it comes across a block it runs the code then continues on through the HTML. So in the example you have working the JavaScript code that alters the image source comes after the element in the HTML which is why it works. In the broken code you call <code>elem=document.getElementById('sunMoon')</code> in the head section, so no element with ID 'sunMoon' exists yet.</p> <p>Generally it is best practice to place your scripts at the bottom of the page (just before the closing tag) so that they run after everything else has loaded, and don't block the rendering of the page. If you were to do that you'd need to change the code that alters the background colour as you can't write it directly to the body tag. The best practice solution would be to apply a different CSS class to the body depending on the time of day and then set up style rules for each class in your CSS.</p> <p>So for example:</p> <pre><code>&lt;script type="text/javascript"&gt; var body = document.getElementsByTagName('body')[0]; var elem = document.getElementById('sunMoon'); if (time&gt;=0 &amp;&amp; time&lt;5) { body.className = 'morning'; elem.src = 'Images/sunMoon1.png'; } else if (time&gt;=5 &amp;&amp; time&lt;10) { body.className = 'afternoon'; elem.src = 'Images/sunMoon2.png'; } &lt;/script&gt; </code></pre> <p>Then in your CSS you need rules for <code>.morning</code>, <code>.afternoon</code> etc</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload