JSFiddle - React, Tailwind, and code Playground
HTML
<div class="content">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
CSS
*{
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome and Opera */
}
.content{
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
cursor: -moz-grab;
cursor: -webkit-grab;
}
.content--slide{
cursor: grabbing !important;
cursor: -moz-grabbing !important;
cursor: -webkit-grabbing !important;
}
.content{
width: 2500px;
}
.item{
width: 500px;
height: 500px;
display: inline-block;
background-color: red;
}
JavaScript
function Swipe(container){
this.$container = container;
this.isMouseDown = false;
this.direction = null;
this.prevX = null;
this.lastScroll = 0;
this.init();
}
Swipe.prototype.init = function () {
this.initEvents();
};
Swipe.prototype.initEvents = function () {
this.$container.on('mousedown', this.mouseDown.bind(this));
this.$container.on('mouseup', this.mouseUp.bind(this));
this.$container.on('mousemove', this.mouseMove.bind(this));
console.info('init events');
};
Swipe.prototype.mouseDown = function (event) {
this.isMouseDown = true;
this.$container.addClass('content--slide')
this.prevX = event.clientX;
};
Swipe.prototype.mouseUp = function (event) {
this.isMouseDown = false;
this.$container.removeClass('content--slide');
this.prevX = null;
};
Swipe.prototype.mouseMove = function (event) {
if(this.isMouseDown){
this.setDirection(event.clientX, this.prevX, this.direction);
console.log(event.clientX, this.prevX, this.direction);
this.scrollContainer(event.clientX, this.prevX);
}
};
Swipe.prototype.setDirection = function (nowX, prevX) {
this.direction = prevX - nowX > 0 ? 'right' : 'left';
};
Swipe.prototype.scrollContainer = function (now, prev) {
var nowOffset = window.pageXOffset;
if(this.direction === 'right'){
$('html, body').scrollLeft(nowOffset + (prev - now) / 10);
} else {
console.log(nowOffset, now, prev)
$('html, body').scrollLeft(nowOffset - (now - prev) / 10 );
}
};
var swipe = new Swipe($('.content'));