Teague
Teague

Reputation: 51

Creating a slideshow with different lengths of time in between

I have a fairly simple slideshow written in jQuery that fades between <div> elements.

In the code below it's set to fade between slides every 5 seconds. Is there a way I can modify this so I can set custom lengths of time to display each slide instead?

Here's a working example on jsfiddle.

My Code

$("#slideshow > div:gt(0)").hide();

    setInterval(function() { 
      $('#slideshow > div:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000)

      setTimeout(function() {$('#slideshow > div:first').appendTo("#slideshow")}, 1000)

    }, 5000);

Upvotes: 2

Views: 1190

Answers (1)

Gass
Gass

Reputation: 9344

You can use an array delay[] to save all the times and create a function slide() with a setTimeout() method to slide through the different images.

Try the following snippet

$("#slideshow > div:gt(0)").hide();

let delay = [1000, 3000, 7000], i = 0;               

function slide() {         
  setTimeout(() => {   
    effect();
    if(i === delay.length){
      i = 0; 
      console.log('Next delay: ' + delay[i] + ' ms');
    }
    else{
      console.log('Next delay: ' + delay[i] + ' ms');
    }
    slide();
  }, delay[i])
  i++;
}

slide();

function effect(){   
    $('#slideshow > div:first')
      .fadeOut(1000)
      .next()
      .fadeIn(1000);

      setTimeout(() => {$('#slideshow > div:first').appendTo("#slideshow")}, 1000)
}
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#slideshow {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#slideshow > div {
  position: absolute;
  overflow-x: hidden;
  overflow-y: hidden;
  width: 100%;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slideshow">

  <div>
    <img src="https://www.port.ac.uk/-/media/images/news-events-and-blogs/news/2020/october/cat-eyes-closed-600x400.jpg">
  </div>

  <div>
    <img src="https://cdn.shopify.com/s/files/1/0997/4496/files/Untitled_design_19_grande.jpg">
  </div>

  <div>
    <img src="https://media.nature.com/lw800/magazine-assets/d41586-020-02779-3/d41586-020-02779-3_18481780.jpg">
  </div>

</div>

Upvotes: 1

Related Questions