Skip to content

Instantly share code, notes, and snippets.

@prashantsani
Last active March 12, 2024 10:37
Show Gist options
  • Save prashantsani/0fa97b54f05bf23cc176a8b54af63b05 to your computer and use it in GitHub Desktop.
Save prashantsani/0fa97b54f05bf23cc176a8b54af63b05 to your computer and use it in GitHub Desktop.
Native Alternate(Vanilla JS) to jQuery's ScrollTo Plugins
const supportsNativeSmoothScroll = 'scrollBehavior' in document.documentElement.style;
function scrollToView(elem) {
if(supportsNativeSmoothScroll){
// https://caniuse.com/#feat=mdn-api_window_scrollto
// As of publish date of this gist,
// this is only supported in 52% browsers,
// So, the next section (`else{`) is a fallback
window.scrollTo({
behavior: 'smooth',
left: 0,
top: elem.getBoundingClientRect().top + window.pageYOffset
});
}else{
// Supported by 97% of browsers
// https://caniuse.com/#feat=scrollintoview
elem.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
}
}
// Usage
// scrollToView(document.getElementById('abc'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment