Reputation: 1274
I have created a simple slider. I want it also for smartphones and not only for desktops. So in this case it should be possible to let it slide when you move your finger from left to right or from right to left. For now it only works when you click on buttons.
I have no idea how to start with it. How can I do this?
var i = 0;
$('.next').bind('click', function() {
if (i < 4) {
$('li').animate({'left': '-=600px'}, 300).delay(600);
i++;
}
console.log($('li:first').position().left);
console.log(i);
});
$('.back').bind('click', function() {
if (i > 0) {
if ($('li:first').position().left < 0) {
$('li').animate({'left': '+=600px'}, 300).delay(600);
i--;
}
}
console.log(i);
});
https://jsfiddle.net/6t1wx95f/11/
PS: It should work without using a plugin.
Upvotes: 1
Views: 5206
Reputation: 7488
I updated your fiddle: https://jsfiddle.net/6t1wx95f/13/
Tested in chrome (in responsive view to have the touch events working). Credit goes to this answer.
Basically, you just need to use touchstart
and touchmove
events. When you touchmove you just take your X position and compare it to where it was when touch-started.
See the touch events docs. It's all in vanilla javascript so you won't have to include any plugin.
// Set up events
var slider = document.getElementsByClassName('slider')[0];
slider.addEventListener('touchstart', handleTouchStart, false);
slider.addEventListener('touchmove', handleTouchMove, false);
..and
if ( xDiff > 0 ) {
/* left swipe */
slideRight();
} else {
/* right swipe */
slideLeft();
}
Upvotes: 3