Recently, I received assistance from this community in creating a script that displays random images from an array within 4 divs. Each image changes upon refresh or with a timer.
HTML:
<section>
<div id="square_1" class='box'>
</div>
<div id="square_2" class='box'>
</div>
<div id="square_3" class='box'>
</div>
<div id="square_4" class='box'>
</div>
</section>
CSS:
body{
width: 100%;
height: 100%;
background-color: #404040;
}
.box{
position: relative;
width: 20%;
background-color: #ffb3b3;
border: 10px solid #fff;
}
.box:before{
content: "";
display: block;
padding-top: 100%;
}
.box img{
width: 100%;
}
/* Positions for the divs */
#square_1{
position: absolute;
margin-top: 2%;
margin-left: 42%;
z-index: 90;
}
#square_2{
position: absolute;
margin-top: 22%;
margin-left: 2%;
z-index: 100;
}
#square_3{
position: absolute;
margin-top: 48%;
margin-left: 27%;
z-index: 100;
}
#square_4{
position: absolute;
margin-top: 34%;
margin-left: 73%;
z-index: 100;
}
Check out how the layout is intended to be: http://codepen.io/anon/pen/ZWYywx
JQuery
/* creating an array of images */
var srcarray = [
"https://s-media-cache-ak0.pinimg.com/736x/7e/1d/4a/7e1d4a1566976f139a2ba58b108e2bce.jpg",
"http://rs832.pbsrc.com/albums/zz248/Paria53/Edited/Random.jpg~c200",
"http://images.freeimages.com/images/premium/large-thumbs/5187/51875120-random-numbers-forming-a-sphere.jpg",
"http://www.islandstone.com/mediafiles/product_records/56_Random_lines_thumb.jpg"
];
function randomizeImages() {
arr = [];
/* selecting unique images from the array and displaying them in relevant divs */
while(arr.length < $("section div").length){
var randomnumber= srcarray[Math.floor(Math.random()*srcarray.length)];
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
$( "section div:nth-child("+(i+1)+")" ).html( '<img src="'+randomnumber+'">' );
};
}
//randomize images on page reload
$(function() {
randomizeImages();
});
//randomize images every 5 seconds
window.setInterval(function(){
randomizeImages();
}, 5000);
Upon associating it with the script, the results can be seen here: http://codepen.io/anon/pen/RaNgvN
I attempted setting top, margin, and padding to zero for <img>
, but it didn't resolve the issue. Any thoughts on what might be causing it or how to resolve it?