Reputation: 183
I'm really getting frustrated with this... I have a solution where the CSS background element originates from a webservice. Currently the system uses HTML to refresh the entire page:
<meta http-equiv="refresh" content="300" />
...
body {
background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700') #1D1F21 top left no-repeat;
background-size: cover;
background-attachment: fixed;
}
This works fine enough, except it triggers an entire page refresh, which is jarring to the end users. I'd like to perform this task in javascript so it's a more elegant transition and doesn't flicker the entire page every x seconds
I cannot figure out why this SetInterval function is not working
$(window).load(function() {
var path=encodeURI('/wallspace/getfile.php?width=gt:1919&height=lt:1700');
$("body").css("background", "url('default-bg.png')");
setInterval(function(){ callback() }, 5000);
function callback() {
// This works so callback is definitely being triggered
//alert("here");
// This only works the first time --is there caching happening?
$('body').css('background', "url('" + path + "')");
}
});
Basically, the callback function is being called at the specified interval but it's not changing the background element. I verified this by calling alert and they are being triggered.
The url of the webservice fetches a random image based on the querystring it recieves in the GET request but it seems like the JQuery is only making the call once and then caching the first response because the background image only changes the first time and then never again until the page is fully refreshed.
Upvotes: 2
Views: 860
Reputation: 183
Thank you @Rory McCrossan and @Robbin 'Roboroads' Schepers
Ensuring the url is different everytime prevents the caching and properly gets a random image!
function callback() {
// Url needs to be unique to prevent caching
var num = Math.floor((Math.random() * 1000) + 1);
$('body').css('background', "url('" + path + "&rand=" + num + "')");
}
You guys here on Overflow are great!
Upvotes: 0
Reputation: 1709
Since path is declared and not being changed, the CSS isn't being changed either. So in CSS, you arn't changing your URL, thus not changing your background.
Try and add random data, like a timestamp:
$('body').css('background', "url('" + path + "&tx="+(new Date()).getTime()+"')");
The reason it works the first time is simple, you are changing
background: url('default-bg.png');
to
background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');
Which is a change.
The second time you change
background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');
to
background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');
Which doesn't change a thing. And since it doesn't change, it does not trigger a reload.
Upvotes: 2
Reputation: 3144
Try replacing
setInterval(function(){ callback() }, 5000);
with
setInterval(callback, 5000);
Upvotes: 0