Randomly move images in a fixed area

I use this code to randomly move images in an area. But I need to show at least 3 images always. Here is what I did:

HTML

<div class="fade">Image 1</div> <div class="fade">Image 2</div> <div class="fade">Image 3</div> <div class="fade">Image 4</div> <div class="fade">Image 5</div> <div class="fade">Image 6</div> 

JQuery

 (function fadeInDiv() { var divs = jQuery('.fade'); var elem = divs.eq(Math.floor(Math.random() * divs.length)); if (!elem.is(':visible')) { elem.prev().remove(); elem.fadeIn(Math.floor(Math.random() * 1000), fadeInDiv); } else { elem.fadeOut(Math.floor(Math.random() * 1000), function() { elem.before('<div>&nbsp;</div>'); fadeInDiv(); }); } })(); 

This code fadein and fadeout images randomly show 2 images at a time, sometimes one image at a time 3. I need to display 3 images with 6 images each time with fadein fadeout functionality.

This is what my homepage looks like:

 Image1 Image2 Image3 

I want it to look like this:

  Image1 Image2 Image3 

or

  Image1 Image2 Image3 

or any other template with these images

+6
source share
2 answers

Try a recursive algorithm with delay lengths depending on the random order of objects:

 window.refresh = function(delay) { delay *= 1000; var doms = []; var randos = []; var index = 0; function fadeout() { if (index < 3) { var random = $(doms.get(randos[index])); $(random).delay(delay + 200 * index).fadeTo(200, 0, function() { $(random).css("visibility", "hidden"); }); doms = doms.not(random); index++; fadeout(doms); } } doms = $('.grid-item'); doms.css("visibility","visible"); doms.css("opacity","1"); var num = Math.floor(Math.random() * doms.length); for (var i = 0; i < doms.length; i++) { while (randos.indexOf(num) > -1) { num = Math.floor(Math.random() * doms.length); } randos.push(num); } fadeout(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="grid"> <div class="grid-item">Image 1</div> <div class="grid-item">Image 2</div> <div class="grid-item">Image 3</div> <div class="grid-item">Image 4</div> <div class="grid-item">Image 5</div> <div class="grid-item">Image 6</div> </div> <br> <button onclick="refresh(0)">Trigger Animation</button> <br> <br> <input type="number" placeholder="Time in Seconds"> <button onclick="refresh($(this).prev().val())">Trigger Delayed Animation</button> 
+1
source

you need to use css properties to change their position on the screen.

You need to clarify your positioning style, absolute IE.

elem.css('top','15px') and elem.css('left','15px') - the propers method for moving objects on the screen. You will adjust 15px to the value you need. This refers to the upper left corner of the screen.

fadeIn / fadeOut only change the opacity property for these objects on the screen.

+1
source

Source: https://habr.com/ru/post/989126/


All Articles