1

I am using jQuery Mobile to allow touch screen users to navigate back and forth in a website with swipe left and swipe right gestures. The problem is that the swipeleft and swiperight events are also triggered with a normal mouse, and that is very annoying because it happens when the user selects some text with the mouse.

You can see the problem on the website itself (http://laetitia-stucki.ch/) and the JavaScript snippet below.

Do you have any idea how to trigger the swipe events only with touch devices and not with a regular mouse?

"use strict";
$( document ).ready( function() {
  ( function() {
    $( "body" ).on( "swiperight", function( e ) { navigate_prev_page(); });
    $( "body" ).on( "swipeleft",  function( e ) { navigate_next_page(); });
    function navigate_next_page() {
      var target_page = $( ".button-next" ).first().attr( "href" );
      window.location.href = target_page;
    }
    function navigate_prev_page() {
      var target_page = $( ".button-prev" ).first().attr( "href" );
      window.location.href = target_page;
    }
  })();
});
nico
  • 808
  • 1
  • 10
  • 18
  • The swipe events work for mouse movements as well as touch gestures. You'll need to identify the device first, and apply swipe events for touch screens only. Check this tread for the subject: http://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery – Gjermund Dahl Mar 31 '16 at 06:41

1 Answers1

1

Thank you Gjermund Dahl for your answer. I followed your link and found another interesting link http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ and finally managed to find a solution. The idea is to disable the swipe event when the mousedown event is triggered and to enable it again when a touchstart event is triggered. I post my solution below. As you can see, jQuery Mobile and Mousetrap libraries can work together.

"use strict";
$( document ).ready( function() {
  ( function() {

    var navigate_to_page = function( e, button_class ) {
      var target_page = $( button_class ).first().attr( 'href' );
      window.location.href = target_page;
    }

    Mousetrap.bind( 'left',       function( e ) { navigate_to_page( e, '.bouton-prec'    ); });
    Mousetrap.bind( 'esc',        function( e ) { navigate_to_page( e, '.bouton-accueil' ); });
    Mousetrap.bind( 'right',      function( e ) { navigate_to_page( e, '.bouton-suiv'    ); });

    $( 'body' ).on( 'mousedown',  function( e ) { disable_swipe( e ); });
    $( 'body' ).on( 'touchstart', function( e ) { enable_swipe( e );  });

    function disable_swipe( e ) {
      $( 'body' ).off( 'swiperight swipeleft' );
    }
    function enable_swipe( e ) {
      $( 'body' ).on( 'swiperight', function( e ) { navigate_to_page( e, '.bouton-prec' ); });
      $( 'body' ).on( 'swipeleft',  function( e ) { navigate_to_page( e, '.bouton-suiv' ); });
    }
  })();
});
nico
  • 808
  • 1
  • 10
  • 18