I am struggling to come up with a clean solution for this:
- The carousel has 7 items, so 0 – 6.
- Index 3 is the middle one
- If for example the 2nd item (index 1) is clicked each item needs to move 2 places to the right. If the last item is clicked (index 6) it would need to move 3 places to the left.
function centerCarouselOn(index, callback) {
var items = $('li', carousel);
var middleIdx = Math.floor(items.length / 2);
var direction = null;
var iterCount = 0;
if(index === middleIdx) return;
if(index > middleIdx) {
direction = 'left';
iterCount = (index - middleIdx);
}
else {
direction = 'right';
iterCount = (middleIdx - index);
}
$('li', carousel).each(function(k, v) {
var li = $(v);
// Here I need to iterate n places to the left or right
// e.g:
// direction = left, iterCount = 3
// Then each li by index would need this sequence:
// 0: 6, 5, 4
// 1: 0, 6, 5
// 2: 1, 0, 6
// 3: 2, 1, 0
// 4: 3, 2, 1
// 5: 4, 3, 1
// 6: 5, 4, 3 (this one moves to center - index 3)
});
}
this does not include any code for animation, and it also assumes that the
carouselelement is the parent<ul>of the<li>s.It should be unnecessary to change the indicies of each
<li>for every ‘move’. All you really need to do is move the last element to the first position, or the first element to the last position (depending on direction you are moving). I also added atimeoutof 1 second so you should be able to see it stepping through.