0

I've written a function that empties a div and inserts a random image from unsplash.com every six seconds using the setInterval function in jQuery. I would like to smooth out the transition using the fadeIn and fadeOut functions, but have been unable to successfully implement this. Below is my code:

function playImageSlideshow() {
  $("#image-slideshow").removeClass("display-none");
  $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "'>");
  setInterval(function() {
    var date = new Date();
    $("#images").empty();
    $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>");
  }, 6000);
}
Ele
  • 33,468
  • 7
  • 37
  • 75

2 Answers2

0

Use the function fadeIn from jQuery.

First Create the img element as follow:

var $img = $("<img class='hide' src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>");

Then, call the faIn function:

$img.fadeIn()

That img is created with a class hide to hide it and then execute the fadeIn effect. Another alternative is execute the hide() function before append this new elemento to your DIV, ie: $img.hide().

Look at this code snippet

let currentCity = 'london';

function playImageSlideshow() {
  $("#image-slideshow").removeClass("display-none");
  $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "'>");
  setInterval(function() {
    var date = new Date();

    var $images = $("#images");
    $("#images img").fadeOut(1000, function() {
      $images.empty();

      var $img = $("<img class='hide' src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>");
      $images.append($img);

      $img.fadeIn(2000);
    });
  }, 3000);
}

playImageSlideshow();
.hide {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='images'></div>

See? now the transition is smoother.

Resource

Ele
  • 33,468
  • 7
  • 37
  • 75
0

Just use the JQuery API and update the image in the setTimeout.

setInterval(function() {
  $("#images").fadeOut(1000);
  $("#images").attr("src", "https://i2.wp.com/www.monicaperezcounseling.com/wp-content/uploads/2017/01/pexels-source-unsplash-4.jpg");
  $("#images").fadeIn(1000);
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="images"/>
Striped
  • 2,544
  • 3
  • 25
  • 31