Antonio Vallez
Antonio Vallez

Reputation: 35

Body Background based on hour of the day JS

<script type="javascript">
jQuery(document).ready(function($){
   var dt = new Date();
   var currentHour = dt.getHours();
   $('body').css('background', '#FFF url(https://crystalforums.cf/bk/bk_'+currentHour+'.png) no-repeat center center fixed');
   $('body').css('background-size', 'cover');
});
</script>

Hey! I had this script working on a my forum and i tried working it on a my website index, but it seems to not work. They both use the body thingy (I forgot the actual term, it's Saturday and i got a ton of work) so they should effect the body element right? What am i doing wrong, the script suppose to set the background image of the website to a new image based on every hour. Help???

I don't want it to auto update, they cxan refresh. I want so there is one background for every hour.

Upvotes: 0

Views: 131

Answers (4)

Sam Huang
Sam Huang

Reputation: 46

You can use the setInterval() function like this:

function someFunction() {
    alert("It's been one hour");
}
setInterval(someFunction, 3600000);

Where the 3600000 is a hour in milliseconds.

Upvotes: -1

guest271314
guest271314

Reputation: 1

You can use setInterval() with duration set to 5 minutes 60000 * 5 or briefer duration between function calls

$().ready(function() {
  var interval, curr;

  function handleBackground() {
    var dt = new Date();
    var currentHour = dt.getHours();
    if (!curr || currentHour !== curr) {
      curr = currentHour;
      $('body').css('background', 'url(https://crystalforums.cf/bk/bk_' 
                   + currentHour 
                   + '.png) no-repeat center center fixed');
    }
  }
  // call `handleBackground` to set initial `background` at `body`
  handleBackground();
  interval = setInterval(handleBackground, 60000 * 5);
});

plnkr http://plnkr.co/edit/5YTPgPgaKbXfYIT0MG3x?p=preview

Upvotes: 0

Sunny
Sunny

Reputation: 402

I don't know JQuery, I always use Java Script :P, If you want to change background after 5 Minutes you can do this by javascript

<script>
index = 0;
function changeBackground(){
var backColor = ["image.jpg","image2.jpg","image3.jpg","image4.jpg"];
document.body.style.backgroundImage = "url("+backColor[index]+")";
index++;
if(index > (backColor.length)  - 1){
index = 0;
}
}
//1000 means 1 second, so for 5 min 
// 6,000 X 5 = 30,000
setInterval(changeBackground, 30000);
</script>

Just try this code.

Upvotes: 0

Sergio Rivas
Sergio Rivas

Reputation: 563

First...I don't recommend use javascript for this....Your approach needs an user for an hour into your website and in the same page...If you still think in change that you will need use setTimeout function...

My recommendation is using a server side technology for this...

Upvotes: 2

Related Questions