Add some effect on the transition between image loading from an array

I found a code that does a random of images in JavaScript at certain seconds, everything is fine.. Only that could you put some effect between images? I try not to make the change so abrupt and dry

Here the Code:

var imagenes=new Array(
  'http://lorempixel.com/500/200/cats',
  'http://lorempixel.com/500/200/people',
  'http://lorempixel.com/500/200/nature'
);

/**
 * Funcion para cambiar la imagen
 */
function rotarImagenes()
{
  // obtenemos un numero aleatorio entre 0 y la cantidad de imagenes que hay
  var index=Math.floor((Math.random()*imagenes.length));

  // cambiamos la imagen
  document.getElementById("imagen").src=imagenes[index];
}

/**
 * Función que se ejecuta una vez cargada la página
 */
onload=function()
{
  // Cargamos una imagen aleatoria
  rotarImagenes();

  // Indicamos que cada 5 segundos cambie la imagen
  setInterval(rotarImagenes,5000);
}
<img id="imagen" />
 2
Author: Alvaro Montoro, 2016-09-21

1 answers

You could use jquery to perform the effect

var imagenes=new Array(
  'http://lorempixel.com/500/200/cats',
  'http://lorempixel.com/500/200/people',
  'http://lorempixel.com/500/200/nature'
);


function rotarImagenes()
{

  var index=Math.floor((Math.random()*imagenes.length));

  $("#imagen").fadeOut(1000, function() {
            $(this).attr('src',imagenes[index]);
        }).fadeIn(1000);
}

$(function(){
  
  rotarImagenes();

  setInterval(rotarImagenes,5000);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<img id="imagen" />

You would be using the fadeOut() and fadeIn() to apply the effect.

Also since you would have jquery use the

$(function() {
  ...
});

To detect when the html DOM is ready

JQuery Change Image src with Fade Effect

 2
Author: Leandro Tuttini, 2017-05-23 12:39:20