Skip to content

Instantly share code, notes, and snippets.

@hoyangtsai
Last active January 13, 2019 08:09
Show Gist options
  • Save hoyangtsai/d1cbc5771d1f2f720f4925ee1c50b209 to your computer and use it in GitHub Desktop.
Save hoyangtsai/d1cbc5771d1f2f720f4925ee1c50b209 to your computer and use it in GitHub Desktop.
Horizontal scroll and svg dot indicator with Hammer gesture
/**
* @horiz-scroll.js
* @author hoyangtsai
* @version 0.1
*/
function HorizScroll(options) {
this.container = options.container;
this.list = options.list;
this.item = options.item;
this.showItemNum = options.showItemNum;
this.init();
}
HorizScroll.prototype.init = function() {
var list = $(this.list);
if (list.children(this.item).length === 0) return false;
function getRem(value) {
return value / parseFloat($('html').css('font-size'));
}
function makeSVG(tag, attrs) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs) el.setAttribute(k, attrs[k]);
return el;
}
var containerWidth = getRem($(this.container).width());
var scrollTimes = Math.floor((list.children(this.item).length - 1) / this.showItemNum);
var curPos = 0;
var counter = 1;
var indic = $('<div />', {
class: 'scroll-indic',
css: {
'text-align': 'center',
'margin-top': '.4rem'
}
});
for (var i = 0; i <= scrollTimes; i++) {
var svg = makeSVG('svg', {
width: '.18rem',
height: '.18rem'
})
var fillColor = i === 0 ? '#de373e' : '#cccccc';
var circle = makeSVG('circle', {
cx: '50%',
cy: '50%',
r: '50%',
fill: fillColor
})
var $svg = $(svg).append(circle);
if (i != scrollTimes) {
$svg.css('margin-right', '.3rem');
}
indic.append($svg);
}
list.after(indic);
var mc = new Hammer.Manager($(this.container)[0]);
mc.add(new Hammer.Swipe({
direction:Hammer.DIRECTION_HORIZONTAL,
}));
mc.on('swipe', function(evt) {
if (evt.direction === 2) {
if (counter > scrollTimes) return false;
indic.children('svg:nth-child(' + counter + ')')
.children('circle').attr('fill', '#cccccc');
curPos = parseFloat(curPos) - parseFloat(containerWidth) - 0.2;
counter ++;
} else if (evt.direction === 4) {
if (counter === 1) return false;
indic.children('svg:nth-child(' + counter + ')')
.children('circle').attr('fill', '#cccccc');
curPos = parseFloat(curPos) + parseFloat(containerWidth) + 0.2;
counter --;
}
list[0].style.left = curPos.toFixed(4) + 'rem';
indic.children('svg:nth-child(' + counter + ')')
.children('circle').attr('fill', '#de373e');
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment