Tuesday, April 29, 2008

JavaScript Background Image Swapper

I'm working on a project that involves displaying a world map on one page. I thought it would be neat to display a nighttime map when the user's local time was between 6pm to 6am. I first tried doing this with server-side C# code but it never really worked correctly so I revisited the problem and instead did the whole thing very simply with JavaScript.

Here's the ASP.Net control I was looking to alter:

<asp:Image ID="imageWorldMap" runat="server" Width="100%" Height="100%" />

And here's the JavaScript that gets called when the page loads:

<script type="text/javascript">
// Set the background according to what time of the day it is on the user's computer.
function SetBackground()
var now = new Date();
var hr = now.getHours();
var img;

if (hr >= 6 && hr < 18)
img = "Images/worldMap.jpg";
img = "Images/worldMapNight.jpg";

document.getElementById('<%=imageWorldMap.ClientID%>').src = img;

No comments:

Post a Comment