jQueryのscrollTop()でスクロール位置を取得することでいろいろなことができるようになる。
目次
ウィンドウ最上部のスクロール位置の取得
$(window).scrollTop()で取得。$(window).on("scroll"だけだとロード時に現在位置が表示されないので$(window).on("load scroll"と記述するのが望ましい。
function getScrollTop(){ $("#result").text($(window).scrollTop() + 'px'); } $(window).on("load scroll", getScrollTop);
jQueryのscrollTop() スクロール位置取得の使い方 サンプル1
ウィンドウ最下部のスクロール位置の取得
$(window).scrollTop()+$(window).height()で取得。ウィンドウ最下部の位置はウィンドウサイズを変更すると変わってしまうため$(window).on("load scroll resize"と記述するのが望ましい。
function getScrollTop(){ $("#result").text($(window).scrollTop() + $(window).height() + 'px'); } $(window).on("load scroll resize", getScrollTop);
jQueryのscrollTop() スクロール位置取得の使い方 サンプル2
ウィンドウ最下部のスクロール位置がある要素まで到達したらイベントを発生させる
最上部から要素までの位置は$("#last").offset().topのようにして取得。
$(window).scrollTop()+$(window).height() >= $("#last").offset().topで到達したときにイベントを発生できるようになる。
var scrollBottom; var lastTop = $("#last").offset().top; function getScrollTop(){ scrollBottom = $(window).scrollTop() + $(window).height(); $("#result").text(scrollBottom + 'px'); if(scrollBottom >= lastTop){ $("#result").text('lastまでスクロールされました'); } else{ $("#result").text(scrollBottom + 'px'); } } $(window).on("load scroll resize", getScrollTop);
jQueryのscrollTop() スクロール位置取得の使い方 サンプル3
offsetTop使用時の注意
jQueryのscrollTop()と違いoffsetTopは親要素までのトップまでの高さを返すので下記のように一番上までの高さが取得できるように工夫が必要。
$(function(){ var elem = document.getElementById("last"); if (elem) { var lastTop = 0; do { lastTop += elem.offsetTop; elem = elem.offsetParent; } while (elem !== null); } function getScrollTop(){ var scrollBottom = $(window).scrollTop() + $(window).height(); $("#result").text(scrollBottom + 'px'); if(scrollBottom >= lastTop){ $("#result").text('lastまでスクロールされました'); } else{ $("#result").text(scrollBottom + 'px'); } } $(window).on("load scroll resize", getScrollTop); });
jQueryのscrollTop() スクロール位置を使用しないサンプル
iPhone, iPadでChromeを使用する際の注意
iPhone, iPadのChromeだとスワイプして下にスクロールしてもスクロールが終了するまで(慣性スクロール中)はscrollTop()で取得した値が表示できないため注意が必要。
IntersectionObserverを使うと処理が軽い
IntersectionObserverを使うとコードの記述が少なく、処理も軽くなる。
IEやSafariでも使用するにはpolyfill.min.jsの読み込みが必要。
let target = document.getElementById('last'); let r = document.getElementById('result'); let observer = new IntersectionObserver(function(changes) { for (let i in changes) { r.textContent = changes[i].isIntersecting ? 'last表示' : 'last非表示'; } });