简体   繁体   中英

Trigger Javascript events only on touch

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM