Reputation: 33
I am making a html page with a image randomizer using code I found somewhere. The code, however, compels me to set a width and a height in pixels. so when I use the code on a div the image does not scale which is bad for the fluid layout I use. (when I set width to auto or 100% in css the image simply doesn't show) how do I alter the code so it works in a fluid layout? here's my css:
.stretcher {
/*#bg {*/
position: absolute;
left: 0px;
top: 0px;
z-index: -69;
width:1366px;
height:768px;
}
the head part of my html:
<script type="text/javascript">
window.onload = function () {
var header = document.getElementById('bg');
var pictures = new Array('bgs/1.jpg','bgs/2.jpg','bgs/3.jpg','bgs/4.jpg','bgs/5.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
header.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
and the div in the body:
<div class="stretcher" id="bg"></div>
Upvotes: 2
Views: 128
Reputation: 2275
use header.style.backgroundImage instead, so it won't override the css, from my comment.
var header = document.getElementById('bg');
var pictures = new Array('http://placekitten.com/g/200/300','http://placekitten.com/g/100/300','http://placekitten.com/g/500/300','http://placekitten.com/g/500/300','http://placekitten.com/g/200/700');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
header.style.backgroundImage = 'url(' + pictures[chosenPic] + ')';
}
.stretcher {
/*#bg {*/
position: absolute;
left: 0px;
top: 0px;
z-index: -69;
width:100%;
height:768px;
background-size: cover;
background-position: middle middle;
background-repeat: no-repeat;
}
.parent {
width:500px;
margin: 0 auto;
}
<div class="parent">
<div class="stretcher" id="bg"></div>
</div>
Upvotes: 0
Reputation: 14590
Probably you can set width
and heigth
to 100% and then the image as background cover
:
CSS:
.stretcher {
position: absolute;
left: 0px;
top: 0px;
z-index: -69;
width:100%;
height:100%;
}
JS:
function cycle() {
var header = document.getElementById('bg');
var pictures = new Array('http://advancement.georgetown.edu/advent/wallpapers/ui/img/1366x768/SealWP_1366x768.jpg', 'http://www.sonymobile.co.jp/xperia/docomo/so-01d/common/download/wallpaper/1366-768/xperiaplaywp_1366-768_bk02.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
header.style.background = 'url(' + pictures[chosenPic] + ')';
header.style.backgroundSize = 'cover';
}
}
cycle();
Upvotes: 2