Wrapping around Flickity for infinite looping

21 Dec 2014 · by David DeSandro

Sliders like Jssor and Slick have the ability to wrap around their cells, making an infinite loop. Users can keep progressing through the gallery without hitting an end. While I'm not sure if this is a good UI pattern (an infinite loop could be disorienting), I imagine that this is a nice feature that people will ask for.

Here's a simple slider you can drag left and right.

See the Pen Wrap around demo 1 by David DeSandro (@desandro) on CodePen.

For this demo, there are only three cells. After cell #3, the next cell should be cell #1. One way to resolve this is to move cell #1 to the end of cell #3 when it's about to be shown. This could work, but it would require moving around all the cells and keeping track of where they are.

Another way is to clone cells so there's overlap to work with. Both Jssor and Slick use this technique.

See the Pen Wrap around demo 2 by David DeSandro (@desandro) on CodePen.

Now the slider can be repositioned when the overlap is visible. The slider position needs to be kept between cellWidth and -sliderWidth + cellWidth, or 0 and sliderWidth if you subtract cellWidth. This math makes use of the remainder operator %.

var modNum = ( ( num % max ) + max ) % max

I've come to learn that is is a modulo operation, which JavaScript lacks. This is a useful operation you might see used when calculating an angle, to keep it between 0 and 360.

// keep angle between 0 and 360
angle = ( ( angle % 360 ) + 360 ) % 360

The tracked position can move outside these bounds, but when it is applied to the rendered position of the slider, then it is wrapped.

See the Pen Wrap around demo 3 by David DeSandro (@desandro) on CodePen.

There's a lot more going on with Flickity — calculating selected cells and applying forces. But the same principle applies. Try flicking all the way around this demo.

See the Pen Flickity - wrap around by David DeSandro (@desandro) on CodePen.


If you're just joining us, I'm making a new gallery library! The story thus far...

Flickity is up on GitHub. Follow along development!