javascript - How to cycle between two arrays -


enter image description here

i'm trying create cycling sliding animation set of elements, have 2 arrays:

var elms = [elm1, elm2, elm3]; var props = [{x,y,width,height,z-index,opacite,....}, {....}, {....}]; 

on initializing, elms positioned in same order props: "-> not part of syntax it's make things easier explain , means 'do with'"

elms[0] -> props[0]; emls[1] -> props[1]; elms[2] -> props[2]; 

but want cycle them like:

elms[0] -> props[2] elms[1] -> props[0] elms[2] -> props[1] 

and then:

elms[0] -> props[1] elms[1] -> props[2] elms[2] -> props[0] 

and forth...

i tried this:

function index(n, array){     var m = n;     if(n > array.length){         m = n - array.lenth;     }else if(n < 0){         m = array.length + n;     }     return m; }  var active = 0; //the front element  function slide(direction){     (i=0; i< elms.length; i++)     {         elms[i] -> props[index(i - active, props)]     }     if(direction == 'fw'){         if(active++ => elms.length){             active = 0;         }else{             active++;         }     }else if(direction == 'bw'){         if(active-- < 0){             active += elms.length;         }else{             active--;         }     } }  setinterval(function(){slide('fw')}, 3000); 

now above code works fine, i'm sure has been done many times before , i'm wondering know if there better less complicated way allows loop forward , backward?

how using module? have global var increment each time shift, module length of arrays. access arrays like: props[shift%len]

if len 3 (as above), these results if accessing props in relation first elmsidx (0):

poc: jsfiddle.net/q8dbb, work without modifying arrays believe faster

shift = 0; // (shift+elmsidx)%len == 0;
shift = 1; // (shift+elmsidx)%len == 1;
shift = 2; // (shift+elmsidx)%len == 2;
shift = 3; // (shift+elmsidx)%len == 0;
shift = 4; // (shift+elmsidx)%len == 1;
etc

actually, using object make more flexible (shifting multiple ways, resetting, whatever want add). here example that:

function shift(len) {     var _len = len;     var _s = 0;     this.left = function() {         _s = (_s + 1)% _len;     }     this.right = function() {         _s = (_s - 1);         if (_s < 0) {             _s = _s + _len;         }     }     this.get = function(idx) {         return (_s + idx)% _len;     }     this.reset = function() {         _s = 0;     } } 

in use: http://jsfiddle.net/6tsup/1/


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -