Reputation: 1
I need some help with this script. Can't find out why it fails sometimes. It is working most of the time, but sometimes it's just showing blank page.
This is the script (in the folders I have 3 image files named 1.jpg, 2.jpg and 3.jpg.:
function chgbg() {
var d = new Date();
var h = d.getHours();
var n = d.getDay();
var totalCount = 3;
var num = Math.ceil(Math.random() * totalCount);
/* Monday - Friday */
if (n >= 1 && n < 5 && h >= 23 && h < 6) {
document.body.style.backgroundColor = "#FFFFFF";
document.body.style.backgroundImage = 'url(gfx/weekdays/00-06/' + num + '.jpg)';
}
if (n >= 1 && n < 5 && h >= 6 && h < 11) {
document.body.style.backgroundColor = "#FFFFFF";
document.body.style.backgroundImage = 'url(gfx/weekdays/06-11/' + num + '.jpg)';
}
if (n >= 1 && n < 5 && h >= 11 && h < 14) {
document.body.style.backgroundColor = "#FFFFFF";
document.body.style.backgroundImage = 'url(gfx/weekdays/11-14/' + num + '.jpg)';
}
if (n >= 1 && n < 5 && h >= 14 && h < 18) {
document.body.style.backgroundColor = "#FFFFFF";
document.body.style.backgroundImage = 'url(gfx/weekdays/14-18/' + num + '.jpg)';
}
if (n >= 1 && n < 5 && h >= 18 && h < 23) {
document.body.style.backgroundColor = "#FFFFFF";
document.body.style.backgroundImage = 'url(gfx/weekdays/18-00/' + num + '.jpg)';
}
/* Monday - Friday */
Upvotes: 0
Views: 54
Reputation: 8995
FYI, in cases like this one I really like to use loops, which iterate over arrays of structures. In this example, each of the cases appear to differ only by: the boundary values for n
and h
, and a substring that will be inserted into the backgroundImage
URL. So, your code loops through this structure and, as soon as it finds a matching case, it uses break
to get out. Much more maintainable.
Upvotes: 0
Reputation: 11
Surely it will fail on the first condition (when your hour is between 23 and 6), because you are telling javascript "if hour is equal to or greater than 23 and less than 6", and this isn't possible.
if (n >= 1 && n < 5 && h >= 23 && h < 6)
A solution could be
if (n >= 1 && n < 5 && (h >= 23 || (h >= 0 && h < 6)))
Upvotes: 1
Reputation: 41075
Your first condition is impossible
if (n >= 1 && n < 5 && h >= 23 && h < 6)
h
can't be both >=23 and <6 at the same time.
Upvotes: 1