Darth Mikey D
Darth Mikey D

Reputation: 109

Javascript slideshow with delay between images

I have the following code to display a slideshow. It works fine, but what I would like to have happen is have the 1st image fade out, there be a delay of a second or 2, and then have the next image fade in. I have this with 2 images right now, but will have multiple images when I finish. Just did 2 for testing right now.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $("#slideshow > div:gt(0)").hide();

    setInterval(function() { 
        $('#slideshow > div:first')
            .fadeOut(5000)
            .next()
            .fadeIn(5000)
            .end()
            .appendTo('#slideshow');
    },  8000);
</script>

<style>
#slideshow { 
    margin: 50px auto; 
    position: relative; 
    width: 240px; 
    height: 240px; 
    padding: 10px; 
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 
}

#slideshow > div { 
    position: absolute; 
    top: 10px; 
    left: 10px; 
    right: 10px; 
    bottom: 10px; 
}

.myslides{
    display: none
}
</style>

<div id="slideshow">
    <div>
        <img src="images/IMG_5434.JPG" width="240" height="240">
    </div>
    <div class="myslides">
        <img src="images/IMG_5435.JPG" width="240" height="240">
    </div>          
</div>

Any thoughts or ideas are appreciated.

Thanks

Upvotes: 2

Views: 1005

Answers (1)

void
void

Reputation: 36703

Use .delay(7000) in the chain. It sets a timer to delay execution of subsequent items in the queue.

Here 7000ms will give you a delay of 2 seconds as your image is fading out in 5000ms.

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

setInterval(function() {
  $('#slideshow > div:first')
    .fadeOut(5000)
    .next()
    .delay(10000)
    .fadeIn(5000)
    .end()
    .appendTo('#slideshow');
}, 8000);
#slideshow {
  margin: 50px auto;
  position: relative;
  width: 240px;
  height: 240px;
  padding: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
}

#slideshow>div {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  bottom: 10px;
}

.myslides {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slideshow">
  <div>
    <img src="https://imagejournal.org/wp-content/uploads/bb-plugin/cache/23466317216_b99485ba14_o-panorama.jpg" width="240" height="240">
  </div>
  <div class="myslides">
    <img src="https://www.w3schools.com/howto/img_fjords.jpg" width="240" height="240">
  </div>
</div>

Upvotes: 1

Related Questions