I don't know if I'm mixing things but I'm not able to change the background gif of a div on a personal project.
I have a div:
<div id="intro" class="view">
....
</div>
And a CSS:
#intro {
background: url("../img/gif1.gif") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
So after load the page, if the user changes the song of the music player I've made a function to change the background gif:
let cover = document.getElementById('intro');
let gifs = ['../img/gif1.gif', '../img/gif2.gif', '../img/gif3.gif', '../img/gif4.gif'];
let actual_gif_index = 0;
function changeGif() { // It's called on the music player
randomGifIndex();
cover.background = "url('" + gifs[actual_gif_index] + "') no-repeat center center fixed";
}
function randomGifIndex() {
let randomIndex = actual_gif_index;
while (randomIndex === actual_gif_index) { //make sure to get the different index
randomIndex = Math.floor(Math.random() * gifs.length);
}
actual_gif_index = randomIndex;
}
But the background doesn't changes... I've tried .style.background
or .style.backgroundImage
but doesn't works too.
Where is my mistake or which property I've to change? I'm a bit confused.
Regards.
-- EDIT --
I've tried .style.background =
but I get a grey background. On the console I can see that the URL it's well-formed and no errors are displayed. If I set the URL explicitly it loads but when it's changed via JS doesn't works.
-- EDIT 2 --
I've found the problem. Apart from having to use the .style.background
property, the main problem was the URL's path as @Espen mentioned. I don't know why, but calling the gifs from the Javascript it's different than call them from the CSS.
On the CSS file I've to use this URL:
#intro {
background: url("../img/gif1.gif") no-repeat center center fixed;
...
}
but on the JS I've to use:
let gifs = ['img/gif1.gif', 'img/gif2.gif', 'img/gif3.gif', 'img/gif4.gif'];
instead of
let gifs = ['../img/gif1.gif', '../img/gif2.gif', '../img/gif3.gif', '../img/gif4.gif'];