0

I have simple html pages on a website with a href id prev and next, so the current page (page two) has two arrows with the following a href ← →:

<a id="prev" href="page-1.html">page one</a>
<a id="next" href="page-3.html">page three</a>

with id="prev" and id="next".

Using the following script, I let users use the keyboard arrows to navigate between next and prev pages:

jQuery(function( $ ) {
var keymap = {};

// LEFT
keymap[ 37 ] = "#prev";
// RIGHT
keymap[ 39 ] = "#next";

$( document ).on( "keyup", function(e) {
var href,
    selector = keymap[ e.which ];
// if the key pressed was in our map, check for the href
if ( selector ) {
    href = $( selector ).attr( "href" );
    if ( href ) {
        // navigate where the link points
        window.location = href;
    }
}
});
});

What I need is a way to use the same id="prev" and id="next" to allow same behavioral navigation using the mobile touch left and right swipe (or add a class to the a or something).

I tried something the following two scripts, but can't get any to work. Can they be edited to add the option to swipe, or is there better script to do that for the same html pages?

1

$(document).on("pageinit",function(){

  var pathname = $(location).attr('href');
  var left = $('#prev').attr("href");
  var right = $('#next').attr("href");

  $("body").on("swiperight",function(){
    <!--alert("You swiped right!");-->
    location.href=right;
  });                       
  $("body").on("swipeleft",function(){
    <!--alert("You swiped left!");-->
    location.href=left;
  });
});
  });

2

var start = null;
 window.addEventListener("touchstart",function(event){
     document.body.innerHTML = "touch";
   if(event.touches.length === 1){
       document.body.innerHTML = " single touch";
      //just one finger touched
      start = event.touches.item(0).clientX;
    }else{
    start = null;
    }
  });

window.addEventListener("touchend",function(event){
    var offset = 100;//at least 100px are a swipe
    if(start){
        document.body.innerHTML = " single touch end";
      //just one finger touched
      var end = event.changedTouches.item(0).clientX;

      if(end > start + offset){
       //a left -> right swipe
      document.body.innerHTML = "next";
      }
      if(end < start - offset ){
       //a right -> left swipe
       document.body.innerHTML = " prev";
      }
    }
  });

P.S.: This is for browsing the site on mobile browsers and not for an app.

Mike
  • 2,051
  • 4
  • 28
  • 46

0 Answers0