Page 1 of 1

Javascript - sort of works but is there a better way?

Posted: Fri 18 Mar 2011 12:31 am
by fractonimbus
I want to change the CSS stylesheet depending whether the sun is up or not (a dark background makes dim images easier to see), so I have a second "night time" CSS that I switch to depending on the time of day. What I have come up with works, but is somewhat messy. I use the Cumulus <#sunrise> parameter which uploads a formatted time like '07:40', which I then parse in Javascript to do the numerical comparison with hours and minutes of the current time. Is there a more elegant solution? [There is also a problem with time zones - see below]

Code: Select all

var d = new Date();
var thours = d.getHours();
var tmins = d.getMinutes();
var sunrise = "<#sunrise>"; // this is replaced by Cumulus with eg '07:40'
var sunset = "<#sunset>"; // this is replaced by Cumulus with eg '18:35'
var srh = parseFloat(sunrise.slice(0,2));  // chop up string and turn into numbers
var srm = parseFloat(sunrise.slice(3));
var ssh = parseFloat(sunset.slice(0,2));
var ssm = parseFloat(sunset.slice(3));
if (((thours == srh && tmins > srm) || (thours > srh)) && ((thours < ssh) || (thours == ssh && tmins <= ssm)))
  { document.write("<link href='weatherstyle.css' rel='stylesheet' type='text/css' />"); }
else
  { document.write("<link href='weatherstyle_night.css' rel='stylesheet' type='text/css' />"); }
Also, I have a concern that this only works in my own time zone - since Javascript uses the local clock on the viewing computer, I think. So, how do I specify the time zone of origin in Javascript?

DN

Re: Javascript - sort of works but is there a better way?

Posted: Fri 18 Mar 2011 12:37 am
by beteljuice
Use <#isdaylight> ;)

1 = Daylight (Including Civil Twilight)
0 = Night

Result is (obviously) local to your station.

Re: Javascript - sort of works but is there a better way?

Posted: Fri 18 Mar 2011 1:29 am
by fractonimbus
Yes, that's **definitely** simpler! I have just been looking at a timezone detecting javascript from https://bitbucket.org/pellepim/jstimezo ... /wiki/Home , which gives the offset from UT, and using that will allow me to trigger on sunset/rise, but the complexity is vastly greater than just using <#isdaylight>

Thanks.

DN

Re: Javascript - sort of works but is there a better way?

Posted: Fri 18 Mar 2011 2:03 am
by beteljuice
If you were to rename your stylesheets to weatherstyle_0.css (night) and weatherstyle_1.css (day) then you wouldn't need JavaScript at all.


html:

<link href='weatherstyle_<#isdaylight>.css' rel='stylesheet' type='text/css' />

Re: Javascript - sort of works but is there a better way?

Posted: Fri 18 Mar 2011 2:30 am
by fractonimbus
Even more elegant! Thanks

DN