Skip to content

Instantly share code, notes, and snippets.

@simevidas
Created June 5, 2020 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simevidas/ff6a69cf46642ff0047f7093b79d354d to your computer and use it in GitHub Desktop.
Save simevidas/ff6a69cf46642ff0047f7093b79d354d to your computer and use it in GitHub Desktop.
// if the URL contains a hash, scroll to the associated heading
if (location.hash) {
let media = body.querySelectorAll('img, video');
let elem = body.querySelector(location.hash);
let mediaPromise = [];
for (let m of media) {
// “<img>/<video> rendered” promises are needed for a scrollIntoView() re-run
mediaPromise.push(
new Promise((res) => {
if (m.tagName === 'IMG') {
if (m.complete && m.naturalWidth) res();
m.onload = () => res();
m.onerror = () => res();
} else if (m.tagName === 'VIDEO') {
if (m.readyState >= 3) res();
m.onloadeddata = () => res();
m.onerror = () => res();
}
})
);
}
setTimeout(() => {
elem.scrollIntoView({ top: 'start' });
Promise.all(mediaPromise).then(() =>
elem.scrollIntoView({ top: 'start' })
);
}, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment