interactjs
"event.dx" test
by cent cent
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="root">
<div class="wrapper">
<div class="card">
<img src="https://source.unsplash.com/user/omarlopez1/AjO8d3il_ns/200x200" alt="Collection">
</div>
<div class="card">
<img src="https://source.unsplash.com/user/branislavisko/vChTLx-QIz0/200x200" alt="Collection">
</div>
<div class="card">
<img src="https://source.unsplash.com/user/madisonccompton/FOpqUzWcamc/200x200" alt="Collection">
</div>
</div>
</div>
<div class="console"></div>
CSS
.root {
position: relative;
overflow: hidden;
background: lightgray;
height: 200px;
width: 400px;
border: 2px solid blue;
margin: 0;
padding: 0;
}
.wrapper {
position: absolute;
left: 0;
top: 0;
width: auto;
transform: translateX(0);
white-space: nowrap;
}
.card {
margin: 0 100px;
display: inline-block;
}
.console {
background: #4d4d4d;
color: white;
min-height: 10px;
margin: 10px 0;
padding: 10px;
}
JavaScript
var printer = $('.console');
var wrapper = $('.wrapper');
var X = 0;
var maxLeft = 0;
var tmp = $('.card').length - 1;
$('.card').each(function(ndx){
if(ndx < tmp){
maxLeft += $(this).outerWidth(true);
}
});
interact($('.wrapper')[0]).
draggable({
startAxis: 'x',
lockAxis: 'x',
restrict: {
restriction: "self"
},
autoScroll: true,
inertia: true,
onstart: function(e){
var x = parseInt(e.dx * 100, 10) / 100;
printer.text(x);
},
onmove: listener,
onend: function(e){
var x = parseInt(e.dx * 100, 10) / 100;
printer.text(printer.text() + ', ' + x);
}
});
function listener(e){
var dx = parseInt(e.dx * 100, 10) / 100;
var tmp = X + dx;
var moveLeft = (dx < 0);
var moveRight = (dx > 0);
if(moveLeft){
if(tmp <= -maxLeft){
X = -maxLeft;
}else{
X = tmp;
}
wrapper.css('transform', 'translateX(' + X + 'px)');
}else if(moveRight){
if(tmp >= 0){
X = 0;
}else{
X = tmp;
}
wrapper.css('transform', 'translateX(' + X + 'px)');
}
//printer.text(printer.text() + ', ' + wrapper.css('transform'));
printer.text(printer.text() + ', ' + X);
//printer.text(printer.text() + ', ' + dx);
}
/*
* Function NOT used!
* `obj` a jQuery object.
* https://stackoverflow.com/questions/21987596/get-css-transform-property-with-jquery
*/
function transform(obj){
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
var mat, angle, x, y, a, b;
if(matrix !== 'none') {
mat = matrix.replace(/[^0-9\-.,]/g, '').split(',');
x = mat[12] || mat[4]; //translate x
y = mat[13] || mat[5]; //translate y
a = mat[0];
b = mat[1];
angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
} else {
x = y = angle = 0;
}
return {x: x, y: y, deg: angle};
}