Created
June 10, 2024 19:32
-
-
Save maoueh/f8baa7bceb3029578ed2e23d7655ec92 to your computer and use it in GitHub Desktop.
45 lines of TypeScript I used to from https://davidwalsh.name/detect-node-insertion
This file contains 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
// Credits to https://davidwalsh.name/detect-node-insertion for the technique | |
type NodeInsertedHandler = (node: HTMLElement) => void; | |
const ANIMATION_PREFIX = "uniqe-animation-prefix"; | |
const handlers: Record<string, { selector: string; onNodeInserted: NodeInsertedHandler }> = { | |
'some-unique-id': { | |
selector: 'div[role="tablist"]', | |
onNodeInserted: (node: HTMLElement) => { console.log(node) }, | |
}, | |
'some-other-selector': { | |
selector: 'body > div:nth-child(26)', | |
onNodeInserted: (node: HTMLElement) => { console.log(node) }, | |
}, | |
}; | |
// @ts-expect-error Chrome + Firefox only, see blog post (link above) for more details | |
document.addEventListener( | |
'webkitAnimationStart', | |
(event: AnimationEvent) => { | |
const name = event.animationName.replaceAll(ANIMATION_PREFIX + '-', ''); | |
const handler = handlers[name]; | |
if (!handler) { | |
return; | |
} | |
handler.onNodeInserted(event.target as HTMLElement); | |
}, | |
false, | |
); | |
// Do we have "string builder" like pattern in JS? | |
let nodeInsertionCSS = ''; | |
for (const [animationName, { selector }] of Object.entries(handlers)) { | |
nodeInsertionCSS += ` | |
@keyframes ${ANIMATION_PREFIX}-${animationName} { from { opacity: 0.99; } to { opacity: 1; } } | |
${selector} { animation-duration: 0.001s; animation-name: ${ANIMATION_PREFIX}-${animationName}; } | |
`; | |
} | |
const rootStyle = document.createElement('style'); | |
rootStyle.textContent = nodeInsertionCSS; | |
document.head.prepend(rootStyle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment