Utilizing SetInterval for dynamically changing the CSS background image URL

I'm starting to feel frustrated with this situation... I have a solution where the CSS background is coming from a webservice. Currently, the system refreshes the entire page using HTML:

<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;
}

Although this method works, it causes a full page refresh, which can be disruptive for users. I would prefer to handle this task in JavaScript for a smoother transition without the flickering every few seconds.

I am struggling to understand why the SetInterval function is not functioning as expected

  $(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() {
      // The alert confirms that callback is being triggered
      //alert("here");

      // However, this only changes the background image the first time -- could there be caching?
      $('body').css('background', "url('" + path + "')");
    }
 });

In essence, the callback function is called at the specified interval but does not update the background element. Running an alert verifies that the function is indeed triggered.

The webservice URL fetches a random image based on the querystring it receives in the GET request, yet it appears that JQuery is fetching the image only once and then caching it because the background image changes initially but never again unless the page is completely refreshed.

Answer â„–1

When you have a path that is declared and not modified, the CSS associated with it remains unchanged as well. Therefore, when your URL in CSS stays the same, the background does not update.

To resolve this issue, try adding some random data, such as a timestamp:

$('body').css('background', "url('" + path + "&tx="+(new Date()).getTime()+"')");

The reason why it works initially is because you are changing

background: url('default-bg‌.png');

to

background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');

which counts as a change.

However, on the second instance, you are changing

background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');

to

background: url('/wallspace/getfile.php?width=gt:1919&height=lt:1700');

This modification does not alter anything, thus failing to trigger a reload.

Answer â„–2

Consider substituting

setInterval(function(){ callback() }, 5000);

for

setInterval(callback, 5000); 

Answer â„–3

Big thanks to @Rory McCrossan and @Robbin 'Roboroads' Schepers for their help!

By ensuring that the URL is different each time, we can avoid caching issues and effectively display a random image.

   function callback() {
      // It's important for the URL to be unique to prevent caching
      var num = Math.floor((Math.random() * 1000) + 1);

      $('body').css('background', "url('" + path + "&rand=" + num + "')");
    }

I really appreciate the support and knowledge shared by everyone here on Overflow!

https://i.sstatic.net/XdzN7.jpg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

Trigger an endless loop upon window.onload event

Every now and then, when a user opens the page, it starts flickering and resizing itself. After checking the log, it appears that the submit function is being called multiple times, but I can't reproduce this issue in my own environment. Is there som ...

Steps to keep only one submenu open at a time and close others

Struggling to figure out how to open one submenu at a time, and I can't seem to locate the issue! I've searched around for solutions but haven't found anything that works for me. The submenu also needs to remain closed when the page loads. - ...

Updating Text in Backbone.js Event

Is there a way to activate a change event on a text box within a backbone view? I attempted the following: events: { "onChanged input.autocomplete": "update" } The update fu ...

Apache Wicket - Utilizing HTML5 details element within a RepeatingView to save open property

In my repeatingview, I have HTML5 detail elements that can be opened or collapsed by the user. However, when I remove certain elements from the repeatingview and then reload it using target.add(container), all elements end up being collapsed again. How c ...

Unused Vue Chart JS options are neglected

I'm encountering an issue with Vue Chart JS v3.5.1 in my Nuxt JS/Vue project where when trying to pass options as a prop, the chart defaults back to its default settings and does not reflect the changes I made. My project includes multiple files: pl ...

Tips for anchoring an element when scrolling reaches its highest point

Is there a way to keep a div element fixed in its original place when scrolling through it, so that it locks into position once we reach a certain point? I've tried using CSS position:fixed; without success. I have noticed this technique on many webs ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

Creating a stylish gradient text color with Material-UI's <Typography /> component

Is there a way to apply a gradient font color to a <Typography /> component? I've attempted the following: const CustomColor = withStyles({ root: { fontColor: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", }, })(T ...

Ways to boost CSS transform with GPU acceleration

Is there a way to ensure smooth animations by utilizing GPU acceleration for CSS transforms in browsers? When does this acceleration occur and how can it be forced? For more information, check out this article ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

The random sorting algorithm in the query_posts function is disrupting the formatting of the CSS

<?php query_posts($query_string . '&orderby=rand') ?> Hello everyone, I recently added the code snippet above to my portfolio page template.php. You can view it at However, I've noticed that sometimes the CSS breaks when you rel ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

What prevents Django websites from being embedded within another HTML (iframe)?

I attempted to include a Django form within another HTML page, but it's not functioning correctly. I've tried on several of my other Django sites with no success. I even tested it on other websites as well. Is there a restriction on using Django ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

I am searching for a Nodejs library that has the ability to serialize and deserialize paths composed of named components, such as URL pathnames. Can

Here is an example: formatPath("/:item1/:item2/:item3", {item1: "apple", item2: "banana", item3: "cherry"}) => /apple/banana/cherry deserializePath("/:item1/:item2/:item3", "/apple/banana/cherry") => {item1: "apple", item2: "banana", item3: "cher ...

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

The latest value has replaced the state's previous value

In my current function, I am updating an array stored in state based on the status of 9 tables. Each table calls this function to check its status, and if true, it is added to the array. const [projectSpaceTypeWarning, setProjectSpaceTypeWarning] = useSta ...