This jQuery script will crossfade backgrounds every 2 hours depending on the time of day. It will also be synchronous for all users as it starts cross-faded between two backgrounds if we're in between two time blocks.
var timeBetweenBackgrounds = 7200000; // in milliseconds - change this to 7200000 for 2 hour between every image
var d = new Date();
var hour = d.getHours();
var minutes = d.getMinutes();
var bgNumber = getPicture(hour);
$(document).ready(function() {
// Determine starting background images:
if (bgNumber < 11) {
var bgNumberNext = bgNumber + 1;
}
if (bgNumber == 11) {
var bgNumberNext = 0;
}
$('#backgroundOne').addClass('bg-' + bgNumber);
$('#backgroundTwo').addClass('bg-' + bgNumberNext);
// Get time overshoot (i.e. how far (in percentage) are we in a certain time-block):
// Every block is 2 hours, so 1 hour into a block would be 50% (0.50)
// Every minute would be 1/120th of a block (minutes / 60 * 0.50)
var timeovershoot= 0;
// Add 50% to the current block if we're in the second hour of a block (see hour definition on the bottom and adjust this if necessary):
if (hour == 0 || hour == 22 || hour == 20 || hour == 18 || hour == 16 || hour == 14 || hour == 12 || hour == 10 || hour == 8 || hour == 6 || hour == 4 || hour == 2){
timeovershoot= timeovershoot + 0.5;
}
// Calculate minute overshoot and add this to the time overshoot:
minuteovershoot= (minutes/60)*0.5;
timeovershoot= timeovershoot + minuteovershoot;
// Calculate time remaining till this block ends (to determine how long to continue fading for):
percentageOfBlockDone= timeovershoot;
percentageOfBlockRemaining= 1-percentageOfBlockDone;
secondsInBlockRemaining= timeBetweenBackgrounds * percentageOfBlockRemaining;
console.log('CURRENT TIME IS: ' + hour + ':' + minutes + '. STARTING BACKGROUNDS ARE: bg-' + bgNumber + ' (opacity ' + percentageOfBlockRemaining.toFixed(2) + ', fading OUT); bg-' + bgNumberNext + ' (opacity ' + percentageOfBlockDone.toFixed(2) + ', fading IN).')
// Set opacity values adjusted to percentage of current block that has elapsed:
// We're fading div ONE out, so this will have an opacity of...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.