本記事では、JavaScriptのscrollイベントの使い方についてサンプルコードを用いて分かりやすく解説しています。
scrollイベントとは、ページがスクロールされたタイミングで発火するイベントです。

- 誰でも分かるように嚙み砕いて説明してくれる
- アニメーションの知識が深く学べる
- 1つのWebサイトを作りながら学べる


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
変数名/関数名にもう悩まない!


- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる


scrollイベントの使い方



scrollイベントは、addEventListenerメソッドにscrollを指定する方法とonscrollプロパティを使う2種類あります!



使い方をそれぞれ別々に解説してるよ!
addEventListenerメソッドを使ったscrollイベントの書き方
addEventListenerメソッドを使ってscrollイベントを登録する時の書き方は以下の通りです。
window.addEventListener('scroll',function(){
// スクロールイベントの処理を記述
});
windowオブジェクトに対してaddEventListenerメソッドを使います。第一引数に「scroll」を指定し、第二引数に指定した関数内にページがスクロールされた時に実行したい処理を記述します。



scrollを使ったサンプルコードは以下の通りです。
上記サンプルでは、ページがスクロールされると表示されているスクロール量の値が変化します。試しにサンプルのページをスクロールしてみると値が変化していることが確認できます。
onscrollプロパティの書き方
onscrollプロパティを使ってscrollイベントを登録する時の書き方は以下の通りです。
window.onscroll = function(){
// スクロールイベントの処理を記述
};
addEventListenerメソッドと同様にwindowオブジェクトに対して、onscrollプロパティを使い関数を代入します。代入した関数にページがスクロールされたタイミングで実行したい処理を記述します。



onscrollプロパティを使ったサンプルコードは以下の通りです。
上記サンプルの処理は、addEventListenerメソッドを使ったものと同様で、ページがスクロールされると表示されているスクロール量の値が変化していきます。
addEventListenerメソッドのscrollイベントとonscrollプロパティの違い



scrollイベントの2種類の書き方について理解できたのですが、2つの違いはあるんですか?



大きな違いとしてイベントを複数登録できるか、できないかの違いがあるよ!
これについては別記事で詳しく解説しているから興味のある方は下記のURLを参考にしてね!


まとめ
今回はJavaScriptのscrollイベントの使い方について解説しました。最後にポイントを軽くおさらいしましょう。
- scrollイベントとは、ページスクロールされたタイミングで発火するイベント
- addEventListenerメソッドで登録するscrollイベントとonscrollプロパティを使ったイベント登録の違いは複数のイベントを登録できるか、できないか