0
0

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 3 years have passed since last update.

IntersectionObserverのAPI

Posted at

#監視API

IntersectionObserverのAPIは非常にシンプルです。IntersectionObserverオブジェクトを作成し、交差を監視したい要素をobserveするだけです。

以下は例である。

// IntersectionObserverオブジェクトを作成する。
// 交差時に実行するコールバック関数を渡す。
const observer = new IntersectionObserver((entries) => {
  for(const e of entries) {
    console.log(e);
  }
});

// 監視したい要素をobserveする。
observer.observe(document.querySelector('.target'));

使い回し用。
main.js

document.addEventListener('DOMContentLoaded', function () {

    const cb = function (el, isIntersecting) {
        if(isIntersecting) {
            //行いたいこと
        }
    } 

    const so = new ScrollObserver(//キーとなるクラス⇨'.cover-slide', cb);
});

scroll.js

class ScrollObserver {
    constructor(els, cb, options) {
        this.els = document.querySelectorAll(els);
        const defaultOptions = {
            root: null,
            rootMargin: "0px",
            threshold: 0,
            once: true
        };
        this.cb = cb;
        this.options = Object.assign(defaultOptions, options);
        this.once = this.options.once;
        this._init();
    }
    _init() {
        const callback = function (entries, observer) {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    this.cb(entry.target, true);
                    if(this.once) {
                        observer.unobserve(entry.target);
                    }
                } else {
                    this.cb(entry.target, false);
                }
            });
        };

        this.io = new IntersectionObserver(callback.bind(this), this.options);

        // @see https://github.com/w3c/IntersectionObserver/tree/master/polyfill
        this.io.POLL_INTERVAL = 100;
        
        this.els.forEach(el => this.io.observe(el));
    }

    destory() {
        this.io.disconnect();
    }
}

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?