Ways to update or refresh a background image without having to reload the entire webpage

I'm facing an issue with an animated gif that plays spinning gears for 1 second and then stops. I have a static image that loads first, which is replaced by the gif when it is clicked to make the gears spin. While this functionality works as intended on the first click, the gif animation fails to play on the second click unless the page is refreshed. However, refreshing the entire page is not an ideal solution for me since the animated gif is used to display a div below the gears when clicked. The gif is set as a background image. Is there a way to simply reload or refresh the gif background image/gif upon clicking?

<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
    <style>
        #gear-box{
            height: 80px;
            width: 50px;
            cursor: pointer;
        }
        .turngears{
            width: 80px;
            height: 50px;
            background: url('image/GearsBaseStatic.png') no-repeat; 
        }
        
        .spingears{
            width: 80px;
            height: 50px;
            background: url('image/GearsBase.gif') no-repeat;
            background-size:74px 45px;
            
        }
        
    </style>
<body>

    <div id="gear-box">
        <div id="gears" class="turngears">
        </div>
        
    </div>
<div>

    <script>
    var gear = document.getElementById('gears');
        
    gear.addEventListener('click',function(gear){
        gear.target.classList.toggle('spingears')
    })

</script>
</body>
</html>  

Answer №1

If you want to reload only the gif, you can modify the URL by adding a parameter at the end that changes every time.

In the following code snippet, the background image URL includes a "?update=" query. With each click, an additional character is appended to it, prompting the browser to fetch a new version of the image when that specific class is applied. To avoid excessive string length, a more advanced approach could involve adding a digit after the update parameter. However, whether this optimization is necessary depends on the anticipated number of clicks.

<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
    <style id="gearstyle">
        #gear-box{
            height: 80x;
            width: 50;
            cursor: pointer;
        }
        .turngears{
        width: 80px;
            height: 50px;
            background: url('https://i.sstatic.net/noWxL.jpg') no-repeat; 
        }
        
        .spingears{
            width: 80px;
            height: 50px;
            background: url('https://i.sstatic.net/Ewreb.giff?update=1') no-repeat;
            background-size:74px 45px;           
        }
        
    </style>
</head>
<body>

  <div id="gear-box">
    <div id="gears" class="turngears">
    </div>    
  </div>
<div>
<script>
let gears = document.getElementById('gears');
let gearStyle = document.getElementById('gearstyle');
gears.addEventListener('click',function(event){
  gears.classList.toggle('spingears');
  gearStyle.innerHTML = gearStyle.innerHTML.replace('?update=','?update=1'); //adds another character to the update string
})
</script>
</body>

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 parse a JSON file in Angular?

Can you please explain how to read a JSON file? I have been able to successfully read a JSON file using a controller, but when I try to read it from a factory, the content is null. Why is this happening? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview ...

Switching the marginTop property when the mouse leaves the div

I'm trying to create a toggle function that slides a div up and down. However, I'm struggling with how to make it toggle marginTop -200 on mouseleave. Do I need a separate function for mouseleave? $(document).ready(function() { $('.men ...

I'm encountering a major issue trying to properly position a background image to fill the entire screen

I am struggling to set a background image that fits the entire screen. It looks great on Windows, but when I view the same page on my mobile device (specifically Android using Google Chrome), the image zooms in and out oddly. Additionally, there seems to b ...

Winning awards through the evaluation of possibilities

I became intrigued by the idea of using a chance algorithm to simulate spinning a wheel, so I decided to create some code. I set up an object that listed each prize along with its probability: const chances = { "Apple" : 22.45, & ...

[Vue alert]: Issue with rendering: "Sorry, unable to read property 'correct_answer' as it is undefined"

My code fetches data from an API. The questions display correctly, but the answers cause an error that crashes the app. Initially, the code worked fine in App.vue, but moving it to a different view page caused the crash. Any suggestions on how to fix this ...

Fade out embedded images or target specific classes when hovering over them with the mouse

Is it feasible to use JavaScript or jQuery to fade only the embedded image instead of the entire div, revealing the background image of the div? I have multiple instances of the classes below and wish to apply these changes only to the selected ones. For ...

Access numerous data points using ajax and php, sans the need for Jquery

Exploring website coding has been an amazing journey for me, and I've come to realize that JavaScript and Ajax play vital roles in creating a standout website. However, my internet research didn't yield very helpful results. Most of the code exam ...

Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page. Currently, I utilize this method to generate a sing ...

Limiting zero is ineffective when it comes to pop-up issues

Hey there, I'm looking to prevent users from inputting zero and dot in a specific field, which is currently working fine. However, when the field is within a pop-up, the code below doesn't seem to work. <script> $('#name').keyp ...

Place a div element in the center

<div class="user-box text-center"> <img src="assets/images/users/user-1.jpg" alt="user-img" title="Mat Helme" class="rounded-circle img-thumbnail avatar-md"> <div class="dropdown"> ...

JQuery ajax event "on drag and drop" is not functioning as expected

I have a collection of images in a <ul><li> with unique IDs for each element. I am trying to trigger a $.ajax call after moving an image to a different location, but it doesn't seem to be working as expected. Here is the HTML code: <scr ...

Transferring request body data between routes in Express: A guide

In my MERN application, there are two specific routes in place. The first route is designated for 'Storing Data' and is referred to as the 'data' route. The second route is used for 'Register User' functionalities and is known ...

Steps for retrieving multiple documents from Firestore within a cloud function

In my cloud function, I have set up a trigger that activates on document write. This function is designed to check multiple documents based on the trigger and execute if/else statements accordingly. I have developed a method that retrieves all documents u ...

Issue encountered while using Axios to send an http request to a server

I am facing an issue when making a GET request to the jasonplaceholder server to fetch data. Sometimes, the request returns undefined for a brief period before fetching all the data. How can I prevent this undefined response and halt the code execution u ...

Discord bot in Node.js, Remove old embed message upon receiving a slash command

My bot is programmed to send an embed message whenever it receives a /xyz command, and the code looks something like this: client.on("interactionCreate", async (interaction) => { if (!interaction.isCommand()) return; const ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

tips for aligning text to the right of an image

For my college project, I am working on a website. However, I have encountered an issue with using a jsp script to display products in a specific way on the webpage. The problem is that I cannot control where the information about price, name, and descript ...

angular click triggers the following content

How can I make the following content appear when clicked? I have a list of content that displays up to 20 items, but I want to show the rest when clicked. I have created the nextMovieList method for this purpose. import { Component, OnInit } from ' ...

Is it possible for Penthouse to retrieve critical CSS while using javascript?

I am currently utilizing the laravel-mix-criticalcss npm package to extract the critical CSS of my website. This package leverages Penthouse under the hood, and you can configure Penthouse settings in your webpack.mix.js within the critical options. The ...