Last active
March 12, 2024 10:37
-
-
Save prashantsani/0fa97b54f05bf23cc176a8b54af63b05 to your computer and use it in GitHub Desktop.
Native Alternate(Vanilla JS) to jQuery's ScrollTo Plugins
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
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