newbieforever
newbieforever

Reputation: 215

Swipe left/right for a webpage

I have a series of enumerated webpages, and at the moment I have a left and a right arrow icon on each page to navigate to the previous/next page in the series.

My question: What is the simplest (!) way to implement swipe left/right gesture to do the same? (No other gestures--no complex solutions please, I am a bloody newbie!)

Thank you very much in advance for your answers!

Upvotes: 5

Views: 14417

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138277

Simply store the first point the user touched down:

 var start = null;
 window.addEventListener("touchstart",function(event){
   if(event.touches.length === 1){
      //just one finger touched
      start = event.touches.item(0).clientX;
    }else{
      //a second finger hit the screen, abort the touch
      start = null;
    }
  });

Then if the finger lefts the screen, check if the offset is higher then a value:

 window.addEventListener("touchend",function(event){
    var offset = 100;//at least 100px are a swipe
    if(start){
      //the only finger that hit the screen left it
      var end = event.changedTouches.item(0).clientX;

      if(end > start + offset){
       //a left -> right swipe
      }
      if(end < start - offset ){
       //a right -> left swipe
      }
    }
  });

You might add additional checks e.g. if the delta y ( clientY) stays under a certain amount, or if the touchmove just goes in one direction. However thats optional and depends if you need to differ it from another swipe action. You could also make the needed swipe dependend off the pages width, e.g.:

var offset = window.clientX * 0.9; // the swipe mist be 90% of the windows size

Test it

Upvotes: 17

Related Questions