2

I'm trying to trigger some JS events only on touch (for showing or not a side menu on a responsive project). I've looked at Hammer.js, followed the basics and here is what I come of with :

var $mainPage = $('#main-page');
  var drawer = 0;
  $mainPage.hammer()
                .on('swiperight', function(e){
                  if(drawer){
                    return true;
                  }
                  $mainPage.css({'transform': 'translateX(260px)', '-ms-transform': 'translateX(260px)', '-webkit-transform': 'translateX(260px)'});
                  drawer = 1;
                })
                .on('swipeleft', function(e){
                  if(!drawer){
                    return true;
                  }
                  $mainPage.css({'transform': 'translateX(0)', '-ms-transform': 'translateX(0)', '-webkit-transform': 'translateX(0)'});
                  drawer = 0;
                });

Everything seems to be fine except it's not only triggering on touch event but with mouse events too. If I try to reproduce the swype with my mouse, it works too... And I don't like it :)

So, I was wondering how I could do it, only firing events only on touch actions.

1 Answer 1

1

Hammer.js will always work with mouse events. Ideally I try to detect touch with Modernizr or using JavaScript and then initialize hammer code.

if (Modernizr.touch) { 
    //your hammer code
}

OR using plain javascript.

var supportsTouch = 'ontouchstart' in document.documentElement;

if(supportsTouch){
  // your hammer code
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.