Skip to content

Instantly share code, notes, and snippets.

@FlynnOConnell
Created December 17, 2022 22:25
Show Gist options
  • Select an option

  • Save FlynnOConnell/8aed7d53d5c28c3d6cc6b98ec88a98c0 to your computer and use it in GitHub Desktop.

Select an option

Save FlynnOConnell/8aed7d53d5c28c3d6cc6b98ec88a98c0 to your computer and use it in GitHub Desktop.

Revisions

  1. FlynnOConnell created this gist Dec 17, 2022.
    67 changes: 67 additions & 0 deletions observers.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@

    export var headerObserver = function (
    toChange: HTMLElement,
    toWatch: any
    ): IntersectionObserverCallback {
    let direction = 'up';
    let prevYPosition = 0;

    const smallheader: any = toChange;
    const sections: any = toWatch;

    const changeHighlight = (selector: string): void => {
    const activelink = smallheader.querySelector(
    `[data-status="active"]`
    ) as HTMLElement;
    const currentlink = smallheader.querySelector(
    `[id="${selector}"]`
    ) as HTMLElement;
    activelink.dataset.status = 'inactive';
    currentlink.dataset.status = 'active';

    return;
    };

    const getTargetSection = (entry: any) => {
    const index = sections.findIndex(
    (section: any) => section == entry.target
    );

    if (index >= sections.length - 1) {
    return entry.target;
    } else {
    return sections[index + 1];
    }
    };

    const shouldUpdate = (entry: any) => {
    if (direction === 'down' && !entry.isIntersecting) {
    return true;
    }

    if (direction === 'up' && entry.isIntersecting) {
    return true;
    }

    return false;
    };

    const onIntersect = (entries: any[]) => {
    entries.forEach((entry: any) => {
    if (window.scrollY > prevYPosition) {
    direction = 'down';
    } else {
    direction = 'up';
    }
    prevYPosition = window.scrollY;

    const target =
    direction === 'down' ? getTargetSection(entry) : entry.target;

    if (shouldUpdate(entry)) {
    changeHighlight(target.dataset.id);
    }
    });
    };
    return onIntersect;
    };