Skip to content

Instantly share code, notes, and snippets.

@jackmcpickle
Created October 17, 2017 23:36
Show Gist options
  • Save jackmcpickle/a74b96ca5caaab7f931627847daf363c to your computer and use it in GitHub Desktop.
Save jackmcpickle/a74b96ca5caaab7f931627847daf363c to your computer and use it in GitHub Desktop.
an working but buggy attempt at using IntersectionObserver to scrollSpy
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;
@jackmcpickle
Copy link
Author

Seems using the IntersectionObserver maybe not the best option. Returns entries from the observer callback in the order of scrolling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment