I’m trying to write code that works WITHOUT "on hover" or any other triggers. This is just an example with the hover event. I just want the images to continuously appear one by one without any trigger. I believe it is very possible, but not sure how to actually do it. I’ve written the code I’ve right now. Any help would be great!
var western = ["https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png", "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Apple_Pay_logo.svg/2560px-Apple_Pay_logo.svg.png", "https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Klarna_Payment_Badge.svg/2560px-Klarna_Payment_Badge.svg.png"];
function getRandomWesternImage() {
var index = Math.floor(Math.random() * western.length);
return western[index];
}
$("#western-wrapper").hover(
function() {
var image = getRandomWesternImage();
$("#western").attr("src", image);
console.log(image);
for (var i = 0; i < western.length; i++) {
// create the image element
var imageElement = document.createElement('img');
imageElement.setAttribute('src', western[i]);
}
});
$("#western-wrapper").mouseout(function() {
$("#western").attr("src", "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png");
console.log(image);
});
.img2 {
max-width: 110px;
margin-bottom: 0.1px;
}
<span id="western-wrapper">
<img id="western" class="img2" src="https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png" />
</span>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.4/TweenMax.min.js"></script>
3
Answers
To change the image every 5 seconds, try this:
If, for some reason, you want to stop the carousel, call
clearTimeout(imageTimer)
. Otherwise, you do not need to declare and save toimageTimer
.Also, for linear image swapping, try this:
setInterval
: method calls a function at specified intervals.If you want a carousel, you could create a plugin that takes: the target element, the images array, and an update interval in ms.