Skip to content

Instantly share code, notes, and snippets.

@YektaDev
Created October 1, 2024 11:13
Show Gist options
  • Save YektaDev/4a860efbf23324b1cda75a1acff1426c to your computer and use it in GitHub Desktop.
Save YektaDev/4a860efbf23324b1cda75a1acff1426c to your computer and use it in GitHub Desktop.
export class ClassObserver {
private readonly target: Element;
private readonly className: string;
private readonly onClassAdd: () => void;
private readonly onClassRemove: () => void;
private readonly observer: MutationObserver | null;
private hadClass: boolean;
constructor(target: Element, className: string, onClassAdd: () => void, onClassRemove: () => void) {
this.target = target;
this.className = className;
this.onClassAdd = onClassAdd;
this.onClassRemove = onClassRemove;
this.hadClass = target.classList.contains(this.className);
this.observer = new MutationObserver(this.mutationCallback);
this.observe();
}
private mutationCallback = (mutations: MutationRecord[]): void => {
for (let m of mutations) {
if (m.type !== "attributes" || m.attributeName !== "class") continue;
let hasClass = (m.target as Element).classList.contains(this.className);
if (this.hadClass === hasClass) continue;
this.hadClass = hasClass;
hasClass ? this.onClassAdd() : this.onClassRemove();
}
};
public observe(): void {
if (this.observer) this.observer.observe(this.target, { attributes: true });
}
public disconnect(): void {
if (this.observer) this.observer.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment