Reputation: 1332
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;
}
})();
});
Upvotes: 1
Views: 2092
Reputation: 1332
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' ); });
}
})();
});
Upvotes: 1