1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript : 一定範囲のスクロールを検知するしてクラスを付与・除去する

Last updated at Posted at 2020-04-02
  • 指定した要素がブラウザ表示範囲の頂上に来たらクラスを付与する
  • 指定した要素がブラウザの表示範囲からでたらクラスを除去する

という仕様でビジュアルコントロールをするスクリプトです。
言葉だけでは分かりづらいので以下サンプル画面をスクロールしてみてください。

See the Pen range activate script by Kazuyoshi Goto (@KazuyoshiGoto) on CodePen.

「Dummy Text Section 1」のブロックが表示範囲最上部に来たらナビゲーションが出てきます。
「Dummy Text Section 1」が画面外に消えるまでスクロールするとナビゲーションが引っ込みます。

ナビゲーションのレイヤーを「show」というクラスの付与・除去でコントロールしています。
一定範囲だけである要素を表示させる」という、よくある感じのUIです。

こういう細かいネタって案外明文化されていないのでメモしておこうと思います。

JavaScript

window.onscroll = function () {
  scrollToggleClass(".section1", ".fixed-nav", "show");
}
function scrollToggleClass(rangeTarget, addTarget, classname) {
  if($(rangeTarget).length){
    scroll = $(window).scrollTop();
    startPos = $(rangeTarget).offset().top;
    endPos = startPos + $(rangeTarget).outerHeight();
    if (scroll > startPos && scroll < endPos) {
        $(addTarget).addClass(classname);
    } else {
        $(addTarget).removeClass(classname)
    }
  }
}

スクロールを検知したら scrollToggleClass() を動かす処理です。

scrollToggleClass() には範囲対象となる rangeTarget、クラスの取り外しをする addTarget、付与するクラス名 classname を指定します。

rangeTargetの開始位置と終了位置を取得し、あとはウィンドウのスクロール位置に応じてクラスを付けたり外したりしています。

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?