With issues related to items using a while loop

I would like to iterate over the collection of divs and randomly fade when the click event fires, but at the moment I have to constantly click to completely supplant the remaining divs. I would prefer to click the div and all its divs will accidentally disappear. I added some console.logs to the while loop, and everything seems to be working fine, the problem is that I am trying to fade out the actual elements. If someone can help, will it be great?

Spell here: http://jsfiddle.net/kyllle/sdpzJ/7/

+4
source share
4 answers

Decided to throw it there too. Simplified.

$(function() { var $ctn = $('#container .ctn'); function randomFadeOut() { var $r = $ctn.not($(this)); var e = 0; while (e < $ctn.length) { $r.eq(e).delay(Math.random() * 500).animate({ opacity: 0 }); e++; } } $ctn.hide().click(randomFadeOut).each(function(v) { $(this).delay(50 * v).fadeIn(); }); }); 

http://jsfiddle.net/sdpzJ/15/

+1
source

I'm not sure if I understand your question, but here is a possible solution:

 function randomFadeOut(i){ var random; var e = 0; while (e < ctnLength) { random = Math.random() * 1000; $(ctn[e]).not(i).delay(random).animate({ opacity : 0 }); e++; } } 

This will cause all divs to fade out randomly when you click on one.

I updated your fiddle here .

+5
source

A random number generator outside of your loop - so you only get one random number over and over.

Try the following:

  function randomFadeOut(i){ var random for (var e=0;e<ctnLength;e++) { random = Math.floor(Math.random() * ctnLength); $(ctn[random]).not(i).animate({ opacity : 0 }); } } 

Of course, since this is a random value, the same cells can be selected more than once, which will leave several cells behind.

+2
source

Here is the best and most efficient randomFade function:

 function randomFadeOut(i){ var tmp = ctn.toArray(); tmp.sort( function(){ return Math.floor( Math.random()*3 ) -1; } ); for( var i=0; i<tmp.length; ++i ){ $(tmp[i]).delay(100 * i).fadeOut(); } } 

This way you only go through the array once. I also updated your fiddle to see it in action :)

+1
source

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


All Articles