search
LoginSignup
2
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

マウスデバイスかどうかの判定

タッチデバイスかどうかは

supportTouch.js
var supportTouch = 'ontouchstart' in document;

で判定できますが、window系のタブレットでは、この方法が使えません。

そこで考えたマウスデバイスかどうか判定する方法は、連続したmousemoveが発生した場合に、マウスデバイスと判定する方法です。

detectMovableMouse.js
(function(){

  // over 2 mousemove events fired in 300ms
  var over = 2, period = 300; 

    var count = 0;
    var timer = null;

    var mousemove = function(evt){
        if ( !timer ) {
            timer = setTimeout(function(){
                timer = null;
                count = 0;
            }, period);
            return;
        }
        if ( ++count < over ) {
            return;
        }
        document.removeEventListener('mousemove', mousemove);
        window.movableMouse = true;
        document.documentElement.classList.add('movableMouse');
        fireEvt();
    };

    var fireEvt = function(){
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent('movableMouse', false, false);
        document.dispatchEvent(evt);
    };

    window.movableMouse = false;
    document.addEventListener('mousemove', mousemove);

})();

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
2
Help us understand the problem. What are the problem?