Fork of slideshow jQ
Answer to https://stackoverflow.com/questions/64582916/jquery-slideshow-with-urls-in-variable-fade-between-images
by YeloPartyHat
HTML
<script src="https://concorddentalde.com/wp-includes/js/jquery/jquery.js"></script>
<div class="hero">
<div class="img-container" id="first"></div>
<div class="img-container" id="second"></div>
</div>
CSS
.hero {
height:45%;
height:45vh;
min-height:400px;
background-color:black;
text-align:center;
background-repeat:no-repeat;
background-size:cover;
background-position:50% 50%;
position: relative;
}
.img-container {
background-repeat: no-repeat;
background-size:cover;
background-position:50% 50%;
background-color: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
JavaScript
$(document).ready(function() {
var urls = [
'https://bit.ly/2G6vBPA',
'https://bit.ly/35LCgYb',
'https://bit.ly/2HGEcsW'
];
// Preload the images
var tempImg = []
for (var i = 0; i < urls.length; i++) {
(new Image()).src = urls[i]
}
var currentShown = 0;
// Get the containers
var first = $("#first");
var second = $("#second");
// This shows whether the second object is on top or not
var secondOnTop = true;
// Set the first container's value so that there is something on the screen and load the second image on top.
first.css('background-image', 'url("' + urls[urls.length - 1] + '")');
second.css({
backgroundImage: 'url("' + urls[0] + '")',
opacity: 1
});
// Change the image every X seconds
setInterval(function() {
var animationSpeed = 1000; // In milliseconds
// Increment count
currentShown === urls.length - 1 ? currentShown = 0 : currentShown++;
// Determine which object have which priority
var primaryObj = first;
var auxObj = second;
if (secondOnTop) {
primaryObj = second;
auxObj = first;
}
secondOnTop = !secondOnTop;
// Show aux background
auxObj.css({
backgroundImage: 'url("' + urls[currentShown] + '")',
opacity: 0
});
auxObj.animate({
opacity: 1
}, animationSpeed);
// Change shown object's background and set to 0
primaryObj.animate({
opacity: 0,
}, animationSpeed, function() {
// Change the primary's background to the next in queue
var nextImg = currentShown === urls.length - 1 ? 0 : currentShown + 1;
primaryObj.css('background-image', 'url("' + urls[nextImg] + '")');
});
}, 6000);
});