LoginSignup
10
12

More than 3 years have passed since last update.

【備忘録】【javascript】ページの一番下までスクロールしたかどうかを判定する方法

Last updated at Posted at 2019-06-19

対象がwindowの場合

// 参考: https://ja.javascript.info/size-and-scroll-window
// ブラウザ間の差異をカバーする
// ページ全体の高さを取得する
const scrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);

// 一番下までスクロールした時の数値を取得(window.innerHeight分(画面表示領域分)はスクロールをしないため引く)
const pageMostBottom = scrollHeight - window.innerHeight;

window.addEventListener('scroll', () => {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    // iosはバウンドするので、無難に `>=` にする
    if (scrollTop >= pageMostBottom) {
        console.log('一番下までスクロールしました');
    }
});

対象がelementだった場合

参考: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

要素がスクロールの最後にある場合 true
そうでない場合に false

// ios系はバウンドするので <= としている
element.addEventListener('scroll', () => {
  element.scrollHeight  -  element.scrollTop <= element.clientHeight
});
10
12
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
10
12