Cameron
Cameron

Reputation: 799

How do I select three images at random and then fade them out with a new image?

I'm mainly a PHP developer, and I haven't used jQuery or JavaScript in a long time.

I've looked on Google and on Stack Overflow but couldn't find the exact direction or code that I need to get the job done. Can anyone help?

I'm pulling in 12 random images via PHP and displaying them. I need to select three images at random every two seconds, fade them out, and have three new unique images fade back in, in their place.

Any help would be appreciated.

           <?php
              $logos = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19');

              $randomize = array_rand($logos, 12);
              shuffle($randomize);
              foreach ($randomize as $randomize) {
                echo '<div class="col-3">';
                  echo '<img class="w-100 mt-4" src="assets/img/' . $randomize . '.png" alt="img">';
                echo '</div>';
              }
            ?>

Upvotes: 2

Views: 544

Answers (1)

Cue
Cue

Reputation: 2759

Replicate your array as a variable.

const logos = ['0', '1', '2', '3', ...];

Quick tip, if the array values are sequential, i.e. 0-19, you can just do:

const logos = [...Array(19).keys()]

Create a function that returns N random elements from the array. If you truly want unique randomisation then the examples on this site are plenty and you can use whatever tickles your pickle.

const randomize = (n) => logos.sort(() => 0.5 - Math.random()).slice(0, n);

Give your images a class to identify them i.e. random-image

<img class="w-100 mt-4 random-image" src="assets/img/12.png" alt="img">

Utilising jQuery's animate() method, you can fade out the existing image, change the image src by replacing the filename with the corresponding random array element, then fade in the image.

const images = $(".random-image");

let interval = setInterval(() => {
  let randomImages = randomize(images.length);
  images.each(function (index) {
    $(this).animate({opacity: 0}, 250, function () {
      this.src = this.src.replace(/(.*)\/.*(\.png$)/i, `$1/${randomImages[index]}$2`);
      $(this).animate({opacity: 1}, 250);
    });
  });
}, 2000);

The benefit of animating the opacity in place of the usual fading methods is to retain document flow which will give you that "in-place" fade effect you desire. The fadeIn and fadeOut methods will actually change the display property of your elements which will make them disappear and interrupt the page flow.


Hope this jogs your memory a little.

Upvotes: 1

Related Questions