Skip to content

Instantly share code, notes, and snippets.

@gukandrew
Last active July 17, 2019 13:37
Show Gist options
  • Save gukandrew/bf621aebd77780f0c370e07807ee89d8 to your computer and use it in GitHub Desktop.
Save gukandrew/bf621aebd77780f0c370e07807ee89d8 to your computer and use it in GitHub Desktop.
Smooth scrollToElement after browser render
# when pass id, mean click action on some link, scroll and replace hash in url
# when no id, gets element id to scroll from url hash
export const scrollToElementAfterBrowserRender = (id) => {
if (!window.requestAnimationFrame) {
return;
}
window.requestAnimationFrame(() => {
const url = new URL(document.location.href);
if (!id) {
const search = url.hash.match(/#?element(\d+)/);
id = search && search[1];
} else if (history) {
url.hash = `#element${id}`;
history.replaceState({}, '', url.href);
}
if (!id) {
return;
}
window.setTimeout(() => {
const el = document.getElementById(`element${id}`);
if (el) {
el.scrollIntoView({ behavior: 'smooth' });
}
}, 200);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment