27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WindowsタッチPCにも対応したクロスブラウザのイベント pointer touch mouse click

Last updated at Posted at 2016-02-18

touch と mouse イベント

SP/PCの両方に対応したイベントの振り分けはこれで良かったのですが。

var isTouchDevice = 'ontouchend' in document,
    eventNames    = {
        start: isTouchDevice ? 'touchstart' : 'mousedown',
        move : isTouchDevice ? 'touchmove'  : 'mousemove',
        end  : isTouchDevice ? 'touchend'   : 'mouseup',
        click: 'click'
    };

WindowsのタッチPC+Chromeの組み合わせで、マウスでボタンが効きません。
(画面タッチは効きます)
touch が先に true になってしまうため。

pointer touch mouse click イベントに対応するには

こうすると、SP/PC/タッチ搭載PC どのデバイスでも大丈夫です。

;(function(window, document, undefined) {

    var deviceEvents = {
        Touch     : typeof document.ontouchstart !== 'undefined',
        Pointer   : window.navigator.pointerEnabled,
        MSPointer : window.navigator.msPointerEnabled
    };

    var eventNames = {
        start     : deviceEvents.Pointer ? 'pointerdown' : deviceEvents.MSPointer ? 'MSPointerDown' : deviceEvents.Touch ? 'touchstart' : 'mousedown',
        move      : deviceEvents.Pointer ? 'pointermove' : deviceEvents.MSPointer ? 'MSPointerMove' : deviceEvents.Touch ? 'touchmove'  : 'mousemove',
        end       : deviceEvents.Pointer ? 'pointerup'   : deviceEvents.MSPointer ? 'MSPointerUp'   : deviceEvents.Touch ? 'touchend'   : 'mouseup',
        click     : 'click'
    };

    window.eventNames = eventNames;

})(this, this.document);
;(function($, window, document, undefined) {
    $('.btn').on(eventNames.end, function () {
        // 処理
    });
})(jQuery, this, this.document);
27
27
0

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
  3. You can use dark theme
What you can do with signing up
27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?