Last active
July 17, 2019 13:37
-
-
Save gukandrew/bf621aebd77780f0c370e07807ee89d8 to your computer and use it in GitHub Desktop.
Smooth scrollToElement after browser render
This file contains hidden or 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
# 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