trying to set up random background images for my Jumbotron. Here is what I have so far.
function randomImage() {
var images = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZwkTaJg28-Bxidgfm6FbHyEZ8D5ya1hGMroF05htuwvQqJsY9sQ",
"http://www.shunvmall.com/data/out/193/47120931-random-image.png",
"https://s-media-cache-ak0.pinimg.com/originals/2b/05/14/2b05140a776f25a8047c88fbe2bcbdb9.jpg"
];
var imgAmount = images.length
console.log(imgAmount);
var x = Math.floor(imgAmount * Math.random())
console.log(x);
document.getElementsByClassName('jumbotron')[0].style.background = "url(" + images[x] + ") no-repeat center center fixed";
}
window.onload = randomImage;
This works however on page load the styles defined in my css sheet seem to be overwritten?
.container .jumbotron {
background: url(/static/images/banner-1.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
margin-bottom: 0px;
border-radius: 0px;
}
Is there a way to load these random images and keep the other styles already defined?
Also, another quick question.. I used getElementsByClassName[0] only because I couldn't get querySelector to work. How would I have written this with querySelector?
Changing the style.background
property using JavaScript resets all the background properties (including background-size
as well). You might only want to alter the backgroundImage
property using JavaScript to keep the other background styles defined in your CSS.
document.querySelector('.jumbotron').style.backgroundImage = 'url(...)';
function randomImage() {
var images = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZwkTaJg28-Bxidgfm6FbHyEZ8D5ya1hGMroF05htuwvQqJsY9sQ",
"http://www.shunvmall.com/data/out/193/47120931-random-image.png",
"https://s-media-cache-ak0.pinimg.com/originals/2b/05/14/2b05140a776f25a8047c88fbe2bcbdb9.jpg"
];
var imgAmount = images.length;
var x = Math.floor(imgAmount * Math.random());
document.querySelector('.jumbotron').style.backgroundImage = "url(" + images[x] + ")";
}
window.onload = randomImage;
.container .jumbotron {
background: url(https://placehold.it/300x200) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
margin-bottom: 0px;
border-radius: 0px;
height: 200px;
border: 6px #000 solid;
}
<div class="container">
<div class="jumbotron">
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With