LoginSignup
1
2

More than 5 years have passed since last update.

左ボタン、中央ボタン、右ボタンのマウス押下シミュレート

Posted at

マウス押下のシミュレートは大体の場合 $('#hoge').click() とか $('#hoge').mousedown() とかで済んでしまうのだけど、どのボタンが押されたのかまで指定したい場合は MouseEvent オブジェクトを生成すると良い。

HTML

<div id="hoge">HOGE</div>

JavaScript によるイベント監視

document.getElementById('hoge').addEventListener('mousedown', function(event){
    switch (event.which) {
    case 1:
        console.log('!! Left !!');
        break;
    case 2:
        console.log('!! Middle !!');
        break;
    case 3:
        console.log('!! Right !!');
        break;
    default:
        console.log('!! No-specified !!');
    }
});

JavaScript によるイベント発行

// 左ボタン押下シミュレート
var leftEvent = new MouseEvent('mousedown', {button: 0});
document.getElementById('hoge').dispatchEvent(leftEvent);

// 中央ボタン押下シミュレート
var middleEvent = new MouseEvent('mousedown', {button: 1});
document.getElementById('hoge').dispatchEvent(middleEvent);

// 右ボタン押下シミュレート
var rightEvent = new MouseEvent('mousedown', {button: 2});
document.getElementById('hoge').dispatchEvent(rightEvent);

参考

1
2
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
1
2