javascript onmousewheelでマウスのホイールを動かした時のイベントを取得する

javascript onmousewheelでマウスのホイールを動かした時のイベントを取得する

javascriptで、onmousewheelを使用してマウスのホイールを動かした時のイベントを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

onmousewheel使い方

「onmousewheel」を使用すると、マウスのホイールを動かした時のイベントを取得することが可能です。

/* html内で利用 */
<タグ onmousewheel ="イベント">

/* js内で利用 */
object.onmousewheel = function(){ イベント };

onmousewheel使い方(html内での使用例)

<div id="main" onmousewheel="hoge()" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>hello javascript!!</p>
</div>

<script>

'use strict';

function hoge(){ 
  console.log('ホイールが動きました'); 
};

</script>

onmousewheel使い方(js内での使用例)

<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>hello javascript!!</p>
</div>

<script>

'use strict';

document.getElementById('main').onmousewheel = function(){ 
  console.log('ホイールが動きました');
};

</script>

実行結果は、ホイールを動かした回数だけ、コンソールに「ホイールが動きました」が表示されます。

macのsafari(13.1.1)でも同じです。

また、以下のコードを、

document.getElementById('main').onmousewheel = function(){ 
  console.log('ホイールが動きました');
};

document.getElementByIdと関数をアロー化して、簡潔に記述することもできます。

main.onmousewheel = () => {
  console.log('マウスから離れました');
};

addEventListener

addEventListenerに登録しても、同じ結果となります。

<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
  <p>hello javascript!!</p>
</div>

<script>

document.getElementById("main").addEventListener ( 
  "mousewheel", function(){ console.log('ホイールが動きました')} 
)

</script>

要素内の要素

「onmousewheel」も「addEventListener(mousewheel)」も、親要素にイベントを指定すると子要素にも影響します。

<div id="main" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
    <p id="sub" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #f00606;">hello javascript!!</p>
</div>

<script>

'use strict';

main.onmousewheel = () => {   
    console.log("mainでホイールが動きました");
}

sub.onmousewheel = () => {
    console.log("subでホイールが動きました");
}

</script>

実行結果

サンプルコード

以下は、
要素内でマウスホイールを動かすと、カウントして、カウントした数を表示する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  let count = 0;

  const hoge = () => {

    count++;

    result.innerHTML = count;

  }

  window.onload = () => {

    main.onmousewheel = () => { hoge(); };

  }

</script>

<body>
  <div id="main" class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">
      <p id="result" class="bg-green-500 text-white py-2 px-8 rounded-full mb-3 mt-4">カウント</p>
    </div>

  </div>
</body>

</html>

カウントされていることが確認できます。