Wednesday 15 February 2012

jquery - Javascript Check if random number is the same as last -



jquery - Javascript Check if random number is the same as last -

i have page number of tiles using javascript toggle class on random tile every 2 seconds. want add together check doesn't toggle same tile twice in row. this, doesn't work.

$(document).ready(function () { var gcflip = $('.flip').find('div'); var sameimg; function flip() { if (gcflip.length >= 1) { var nextimg = gcflip[math.floor(math.random() * gcflip.length)]; while(nextimg === sameimg) { var nextimg = gcflip[math.floor(math.random() * gcflip.length)]; } nextimg = sameimg; $(nextimg).toggleclass('transition'); } } setinterval(flip, 2000); });

there few issues here (@a-wolff nail on few keys),

closure scope, moved gcflip & currentimg outside document ready function - nextimg beingness redefined each time within loop. moved flip() function out of beingness defined within doc ready f(x).

you setting 'current image' pointer before transitioned , assignment flipped (no pun intended) resetting nextimg current image before calling transition.

this should closer you're looking for.

var gcflip; var currentimg; $(document).ready(function (){ var gcflip = $('.flip').find('div'); setinterval(flip, 2000); }); function flip() { if (gcflip.length >= 1) { var nextimg = gcflip[math.floor(math.random() * gcflip.length)]; while(nextimg == currentimg) { nextimg = gcflip[math.floor(math.random() * gcflip.length)]; } $(nextimg).toggleclass('transition'); currentimg = nextimg; } }

javascript jquery

No comments:

Post a Comment