Exchanging image with Javascript

Asked

Viewed 156 times

1

I have the following code to automatically change image in Javascript.

I wanted to use it to leave as a gif, without losing the quality.

var index = 1;

function changeImage(){

var rand = Math.floor (Math.random () * 4)
  jQuery('.img-rand').hide();
 
 jQuery(jQuery('.img-rand').get(index)).fadeIn();
 index++;

  if (index > 3){
   index = 0;
  }
}

setInterval(changeImage, 500);
.img-rand{
  display:none;
}
<div class="imagemconjunto ">

<img class="img-rand" src="{{media url="wysiwyg/Paginas/kitbody/profissoes.png"}}" alt="" />
<img  class="img-rand"  src="{{media url="wysiwyg/Paginas/kitbody/profissoes2.png"}}" alt="" />

</div>

But it is a very broken effect. Does anyone know a way to leave with a gif aspect? In the case is the same image, just click here and click on the other without.

  • While analyzing your problem, I’m thinking that you just need to resize the images to be the same size, so this breaking effect will fade

  • Worse than not, if you look at the bottom of the page you will see what I’m talking about https://www.boutiqueinfantil.com.br/testing

1 answer

3


Instead of using setInterval() you could use the recursive function, using the callbacks of the .fadeIn() and of .fadeOut(), making a delay of 500 milliseconds on .fadeOut(). Now, the index should start from 0, and not of 1, in this way:

var index = 0;

function changeImage(){

   var rand = Math.floor (Math.random () * 4)
   jQuery('.img-rand').eq(index).fadeIn(function(){
      jQuery('.img-rand').delay(500).eq(index).fadeOut(function(){
         index++;
         // aqui o "1" é se vc possui 2 imagens
         if (index > 1) index = 0;
         changeImage();
      });
   });
   
}
changeImage();
.img-rand{
  display:none;
  width: 200px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="imagemconjunto ">
   <img class="img-rand" src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" alt="" />
   <img class="img-rand"  src="https://tinyjpg.com/images/social/website.jpg" alt="" />
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.