Skip to content

Instantly share code, notes, and snippets.

@ptrin
Created May 13, 2020 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptrin/e68e0f6fd6c45581034dcb8aa653b36a to your computer and use it in GitHub Desktop.
Save ptrin/e68e0f6fd6c45581034dcb8aa653b36a to your computer and use it in GitHub Desktop.
Adjust scroll position on focus (if necessary)
const oldHTMLFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function () {
oldHTMLFocus.apply(this, arguments);
setTimeout(function() {
const currentScrollPos = window.scrollY || window.scrollTop;
const offset = $(this).offset().top;
// if difference between currentScrollPos and offset from top of document is less than x, adjust
const difference = Math.abs(currentScrollPos - offset);
if (difference < 100) {
window.scrollTo(0, currentScrollPos - 100);
}
}.bind(this), 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment