-1

im trying to write a script to change my body background based on the whether its am or pm, I have the following, only its not working, can anybody see why?

<!-- Change background -->
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 20) {
    if (document.body) {
        document.body.background = "images/backgrounds/day.jpg";
    }
}
else {
    if (document.body) {
        document.body.background = "images/backgrounds/night.jpg";
    }
}
<!-- Change background -->
  • is `<= 7` a typo or the source of the error? Btw, it won't change if it's am / pm but day / night (but you probably know that already). And still btw, i can't see why you tagged your question `jquery` since you are using plain js. – JMax Sep 08 '11 at 14:44
  • im not sure, i tried to take the script from here http://stackoverflow.com/questions/4358155/changing-background-based-on-time-of-day-using-javascript – Nemanja Tenzigl Sep 08 '11 at 14:46
  • Have you wrapped your code with ` – betamax Sep 08 '11 at 14:47
  • Try using `document.body.style.backgroundImage = "url(images/backgrounds/day.jpg)";` – Bojan Dević Sep 08 '11 at 14:56
  • Your code works when you reference existing images: [http://jsbin.com/oboqip/2](http://jsbin.com/oboqip/2) – kalyfe Sep 08 '11 at 14:56

3 Answers3

1

A good idea would be to actually use jQuery selectors and modify the CSS:

$('body').css({
    background: 'url(yourUrl)'
});
0

there maybe several problems with this

1) I can't seem to access those two images. Are they actually at the path you specified?

http://int.test.venndigital.co.uk/correlatesearch/_includes/images/backgrounds/day.jpg http://int.test.venndigital.co.uk/correlatesearch/_includes/images/backgrounds/night.jpg

Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54
0

This should be what you need. You should really try to learn javascript instead of just asking people to write it for you, though. Either that or hire someone else to do the job.

$('body').css('background-image', function(){
  var url, hour = new Date().getHours();
  if (hour > 7 && hour < 20) {
    return 'http://example.com/day.jpg';
  } else {
    return 'http://example.com/night.jpg';
  }
});
coreyward
  • 77,547
  • 20
  • 137
  • 166