I have a grid and each div has a background image. I am trying to create a fade out/in image swapping effect. Currently I'm getting two random divs and inserting one background-image URL into the other. Problem is, after a while all the images wind up the same. I think I need to reset the background URL to the original value (image) each time, but I'm not sure how to do that.
So the order would be: original image fades out, new image fades in, new image fades out, original image fades in
Any help greatly appreciated!
Currently I have this fiddle:
JS:
var $squares = $('.box');
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square2 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square1Url = square1.css('background-image').replace(/(url\(|\)|")/g, '');
var square2Url = square2.css('background-image').replace(/(url\(|\)|")/g, '');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square2Url + ")");
$(this).fadeIn(1500);
});
timeoutId = setTimeout(imgFade, 1500);
}
imgFade();
HTML:
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')"></div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')"></div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')"></div>
</div>
CSS:
body {margin:0}
.grid-container {width:100%;}
.box {
width:20vw;
height:33.33vh;
float:left;
border:1px solid white;
background-size: cover;
background-position:center;
}
Aucun commentaire:
Enregistrer un commentaire