Reputation: 1074
I've written simple swipe functionality on js.
On desktop works fine everything, but on smartphones it doesn't work.
Here is my Javascript:
(function(){
var project = {
dragging: false,
xCordinateDown: null,
yCordinateDown: null,
init:function(){
var swipeObject = document.getElementById('slide');
swipeObject.addEventListener('mousedown', this.taped);
swipeObject.addEventListener('mouseup', this.tapedOut);
swipeObject.addEventListener('mouseleave', this.tapedOut);
swipeObject.addEventListener('mousemove', this.swiped);
},
taped:function(e){
this.dragging = true;
this.xCordinateDown = e.clientX;
this.yCordinateDown = e.clientY;
},
tapedOut:function(){
this.dragging = false;
this.xCordinateDown = null;
this.yCordinateDown = null;
document.getElementById("slide").style.top = 0;
},
swiped:function(e){
if(this.dragging){
var xCordinate = e.clientX;
var yCordinate = e.clientY;
var xDifference = this.xCordinateDown - xCordinate;
var yDifference = this.yCordinateDown - yCordinate;
if(Math.abs(xDifference) < Math.abs(yDifference)){
if(yDifference < 0){
document.getElementById("slide").style.top = Math.abs(yDifference) + 'px';
}
}
}
}
}
project.init();
})();
How can I fix it on smartphones? Where is the problem?
here is jsfiddle: DEMO FIDDLE
thanks in advance
Upvotes: 0
Views: 115
Reputation: 47099
Use dedicated touch events: touchstart
, touchmove
, thouchend
. You have to know that you will have to read the offset from TouchEvent.targetTouches
:
var startCoords = null;
el.addEventListener('touchstart', function(event) {
startCoords = [
event.targetTouches[0].pageX,
event.targetTouches[0].pageY,
];
});
And that the touchend
event wont supply you with targetTouches
.
I did an answer on whats the difference on touchstart
/mousedown
& touchend
/mouseup
is.
Upvotes: 1