Created
October 17, 2017 23:36
-
-
Save jackmcpickle/a74b96ca5caaab7f931627847daf363c to your computer and use it in GitHub Desktop.
an working but buggy attempt at using IntersectionObserver to scrollSpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import throttle from 'lodash/throttle'; | |
import map from 'lodash/map'; | |
class ScrollSpy | |
{ | |
$targets: Element[]; | |
$navItems: JQuery<HTMLElement>; | |
observer: IntersectionObserver; | |
threshold: number; | |
activeClass: string; | |
constructor(ops) | |
{ | |
this.$navItems = $(ops.navItems); | |
this.activeClass = ops.activeClass; | |
this.$targets = this.getTargets(); | |
this.threshold = 0.25; | |
const options = { | |
rootMargin: '0px', | |
threshold: this.threshold | |
} | |
this.observer = new IntersectionObserver(this.callback.bind(this), options); | |
this.$targets.forEach( target => target && this.observer.observe(target) ); | |
} | |
callback(entries, observer) | |
{ | |
entries.forEach(entry => { | |
if(entry.intersectionRatio >= this.threshold) { | |
this.$navItems.removeClass(this.activeClass).blur(); | |
const $navigationItem = this.$navItems.filter(`[href*="#${entry.target.id}"]`); | |
$navigationItem.addClass(this.activeClass); | |
}; | |
}); | |
} | |
getTargets() | |
{ | |
return map(this.$navItems, (nav: HTMLAnchorElement) => document.getElementById( nav.href.split('#')[1]) ) | |
} | |
} | |
export default ScrollSpy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems using the IntersectionObserver maybe not the best option. Returns entries from the observer callback in the order of scrolling.