Using JavaScript to change an image between night and day
Programming Level: 1/5
In the picture below, you can see a city skyline. If you are reading this and it is daytime, you see a daytime picture, and if it is nighttime, you see the city of San Francisco all lit up. I use this on my homepage because I figure this adds a nice touch so that my website has the right feeling whether you are browsing during business hours vs. after hours.
And here's the DHTML and JavaScript Code:
<img id="bannerTop" src="images1/bannerTop.jpg" width="588" height="60">
<script language="javascript"> var nowdate=new Date() var nowhour=nowdate.getHours() if(nowhour>19 || nowhour<7) document.getElementById("bannerTop").src="images1/bannerTopNight.jpg" </script>
How it Works
The first line is the image tag. It is the same as an ordinary image tag, except it has an attribute called ID. The ID attribute will be used by the JavaScript.
You can see in the <script> tag, 4 lines of code. The first two lines of code simply establish what the current hour of the day it is. The "if" statement looks at the hour, and if it's past 19:00 hours (7 o'clock P.M.), OR if it's before 7:00 AM, then it will swap the image my dynamically changing the "src" attribute of the above <img> tag above.
|