'reload the background image from CSS file (JS)
I have a CSS file that contains a background image: in this case it's an animated PNG. This APNG has loop 1, meaning it only plays one time. I have it working that the file reloads but what I now need to have is to get the actual background url from the CSS File
FROM FILE: style.css
.my-div{
background-image: url("img/animation_menu_no_loop.png");
background-repeat: no-repeat;
pointer-events: none;
background-size: contain;
}
<div id="container" class="my-div">some text</div>
The following works fine and restarts the animation when in viewport:
document.getElementById('container').style.backgroundImage = 'url("img/animation_menu_no_loop.png'+'?a='+Math.random() +'")'
but there is only one problem, I have now hard coded the image src as I have taken from the CSS file. But if I update the CSS background I also need to update the 'style.background' line so for this I need to extract the actual URL used in the CSS file. How can I get that out?
I mean extract this section from the CSS file:
"img/animation_menu_no_loop.png"
Solution 1:[1]
I've tried recreating with a similar APNG file, although this one seems to have more frames.. Even so, it replays itself automatically
Is it possible to upload the one you're using and link it in this snippet for testing purposes
div {
width: 200px;
height: 200px;
background-color: gray;
background-repeat: no-repeat;
pointer-events: none;
background-size: contain;
/* background-image: url(https://gifimage.net/wp-content/uploads/2018/05/sparkler-gif-9.gif); */
background-image: url(https://upload.wikimedia.org/wikipedia/commons/1/14/Animated_PNG_example_bouncing_beach_ball.png);
}
<p>Reload GIF</p>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div style="">
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
For your new problem: You can place the value for the url in a variable, like so:
:root {
--my-pnga: img/animation_menu_no_loop.png;
--my-pnga-url: url(img/animation_menu_no_loop.png);
}
Then to use it in the css:
background-image: var(--my-pnga-url);
And to access it with javascript:
let my_pnga = getComputedStyle(document.documentElement)
.getPropertyValue('--my-pnga');
document.getElementById('container').style.backgroundImage = `url("${my_pnga}?a='${Math.random()}'")`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |