K
K
krll-k2015-09-13 23:31:30
JavaScript
krll-k, 2015-09-13 23:31:30

How to implement swipe in native javascript?

touch_events.png
I'm struggling with the fact that I don't know how to calculate an absolutely relative shift (newX, newY):

document.body.addEventLestener("touchmove",function(e){
  if(event.targetTouches.length==1){
    var touch = event.targetTouches[0];
    var x = touch.pageX, y = touch.pageY;
    var newX = ???, newY = ???;
    if(x-newX <= y-newY) ...
  }
},false);

I thought about how to try to solve:
1) make constants (const) from variables x and y, and then set the timer, compare with newX and newY. Right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wimanen, 2017-07-20
@wimanen

We need to add not only touchmove, but also touchstart and touchend.
If you look only along the x-axis, then

var touchStart=  -1,
        touchEnd= -1,
        count= 0,
        targetElem= document.getElementById('some_element');

In the touchstart function, we take the coordinates of the start of the movement:
function tStart(e){
          e = e ? e : window.event;
          e = ('changedTouches' in e)?e.changedTouches[0] : e;
          touchStart = e.pageX;
       }

In the course of touchmove:
function tMove(e){
          e = e ? e : window.event;
          e = ('changedTouches' in e)?e.changedTouches[0] : e;
          touchEnd = e.pageX - touchStart;
          var _count = count -touchEnd;
          targetElem.style.transform = 'translateX('+(-_count)+'px)';
       }

Well, at the end of the touchend movement:
function tEnd(e){
          count = count - touchEnd;
          targetElem.style.transform = 'translateX('+(-count)+'px)'; 
       }

We take the initial values, move the element along our X axis along the way, and "save the result" at the end of the movement.
ps I do not pretend to be true, of course smart people can write more elegantly =))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question