LoginSignup
3

More than 3 years have passed since last update.

JavaScript・jQueryを使用して特定の位置にスライドしたら発火させる【初心者向け】

Last updated at Posted at 2019-10-15

サイトの無限スクロールを自作しようとしたときに実装したものです。
忘れたときのメモ用でもあります。

test.html
<body>
    <div class="body"></div>
    <span class="point">ここが表示されると発火!</span>
</body>
test.css
.body {
    display: block;
    height: 2000px;
}
test.js
$(function(){
    $(window).on('scroll', function() {
        if($(this).scrollTop() + $(window).height() > $('.point').offset().top){
            alert('発火!');
        }
    });
});

一応jsのif文の中身をサクッと解説すると、

$(this).scrollTop()

→ スクロールをしたheightの数値

$(window).height()

→ ブラウザのウィンドウのheightの数値

$('.point').offset().top

→ 画面トップから指定した要素(上記の場合はpointクラス)までのheight

図で表すとこんな感じです。
sample_image_1.png

発火するときはこんな感じです。
sample_image_2.png

多分間違えていないはず!

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
3