Skip to content

Instantly share code, notes, and snippets.

@muthuspark
Created June 26, 2020 12:47
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 muthuspark/82d874085d9d5dad3ed47873ed6ad362 to your computer and use it in GitHub Desktop.
Save muthuspark/82d874085d9d5dad3ed47873ed6ad362 to your computer and use it in GitHub Desktop.
Pure Javascript implementation to Scroll to a particular element on page.
// the code will also try to center the element on the page.
var ElementScrollTo = {
documentVerticalScrollPosition: function() {
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},
viewportHeight: function() {
return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight;
},
documentHeight: function() {
return (document.height !== undefined) ? document.height : document.body.offsetHeight;
},
documentMaximumScrollPosition: function() {
return this.documentHeight() - this.viewportHeight();
},
elementVerticalClientPosition: function(element) {
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},
/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition) {
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived) {
// Apply target.
scrollTo(0.0, targetPosition);
return;
}
// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
// Apply target.
scrollTo(0.0, Math.round(currentPosition));
},
scrollVerticalToElement: function(element) {
if (element == null) {
console.warn('Cannot find element with id \'' + id + '\'.');
return;
}
var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPosition(element) - 20;
var currentPosition = this.documentVerticalScrollPosition();
// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};
// how to use?
ElementScrollTo.scrollVerticalToElement(document.querySelector('#answer'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment