JSFiddle - React, Tailwind, and code Playground
by hmdadou
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<div id="myDiv"></div>
CSS
#myDiv {
width: 100%;
height: 400px; /* adjust height to your liking */
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
JavaScript
// array of image URLs from Flickr
var images = [
'https://images.unsplash.com/photo-1571988840298-3b5301d5109b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80',
'https://images.unsplash.com/photo-1548366086-7f1b76106622?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=376&q=80',
'https://images.unsplash.com/photo-1511694009171-3cdddf4484ff?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80'
];
// index of the currently displayed image
var currentIndex = 0;
// select the div element to apply the background slideshow to
var $div = $('#myDiv');
// function to change the background image
function nextImage() {
// update the current index
currentIndex++;
if (currentIndex == images.length) {
currentIndex = 0;
}
// apply the fading effect to the current image
$div.css('background-image', 'linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 67%, rgba(255,255,255,1) 100%), url(' + images[currentIndex] + ')');
}
// call the function once to set the initial background image
nextImage();
// change the image every 5 seconds
setInterval(nextImage, 5000);