skip to Main Content

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


  1. To change the image every 5 seconds, try this:

    let imageTimer;
    
    function updateImage() {
        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]);
        }
    
        imageTimer = setTimeout(updateImage, 5000);
    }
    
    onload = () => { imageTimer = setTimeout(updateImage, 5000); }
    

    If, for some reason, you want to stop the carousel, call clearTimeout(imageTimer). Otherwise, you do not need to declare and save to imageTimer.

    Also, for linear image swapping, try this:

    let imageTimer, imageIndex = 0;
    
    function updateImage() {
        var image = western[imageIndex];
        $("#western").attr("src", image);
        console.log(image);
        imageIndex++;
        imageIndex *= (imageIndex < western.length);
        // The above line sets imageIndex back to 0 if we reached the end
    
        for (var i = 0; i < western.length; i++) {
            // create the image element
            var imageElement = document.createElement('img');
            imageElement.setAttribute('src', western[i]);
        }
    
        imageTimer = setTimeout(updateImage, 5000);
    }
    
    onload = () => { imageTimer = setTimeout(updateImage, 5000); }
    
    Login or Signup to reply.
  2. setInterval : method calls a function at specified intervals.

    const imgLinks = ["img-url1", "img-url2", "img-url3", "img-url4"];
    
            let pointer = 0;
            const img = document.querySelector("#img");
            const imgLen = imgLinks.length - 1;
    
            //for the first time preview on page load; it can also be set in <img src='img-url'>
            img.src = imgLinks[pointer];
    
            setInterval(() => {
                //if-condition is only useful if we need infinite-time preview (like image would start from 0 if reached last)
                if (pointer > imgLen) pointer = 0;
                img.src = imgLinks[pointer++];
            }, 1000);
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <img id="img" src="">
    </body>
    
    </html>
    Login or Signup to reply.
  3. If you want a carousel, you could create a plugin that takes: the target element, the images array, and an update interval in ms.

    const paymentImages = [
      "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"
    ];
    
    const carousel = new Carousel($('#western'), paymentImages, 2000).start();
    
    setTimeout(() => {
      console.log('Stopping...');
      carousel.stop();
    }, 9000);
    
    function Carousel($el, images, updateMs) {
      this.$el = $el;
      this.images = images;
      this.updateMs = updateMs;
      this.imageTimer = null;
      this.imageIndex = -1;
      this.isRunning = false;
    
      this.updateImage = function() {
        if (!this.isRunning) return;
        this.imageIndex = (this.imageIndex + 1) % this.images.length;
        this.$el.attr('src', this.images[this.imageIndex]);
        this.imageTimer = setTimeout(boundedUpdateImage, updateMs);
      };
    
      const boundedUpdateImage = this.updateImage.bind(this);
    
      this.start = function() {
        this.isRunning = true;
        this.updateImage();
        return this;
      };
      
      this.stop = function() {
        clearTimeout(this.imageTimer);
      
        this.isRunning = false;
        this.imageTimer = null;
        this.imageIndex = -1;
      };
    
      return this;
    }
    #western {
      max-width: 110px;
      margin-bottom: 0.1px;
    }
    <span id="western-wrapper">
      <img id="western" />
    </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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search