Skip to content

Instantly share code, notes, and snippets.

@alestrunda
Created April 28, 2022 07:44
Show Gist options
  • Save alestrunda/c8b1900aa6592d5f0e30ef41872fe23f to your computer and use it in GitHub Desktop.
Save alestrunda/c8b1900aa6592d5f0e30ef41872fe23f to your computer and use it in GitHub Desktop.
Fix screen scroll position to a selected element on window resize
/*
Focus screen scroll position on a selected element when window resizes.
Have you ever developed a responsive design of an element but when you're resizing the window the element is jumping
up and down because the content around resizes too? This simple function will fix the top of the screen to the top
of the selected element when the window resizes. Just define the function in dev console and then run it.
Usage: resizeFocuser('div.element-to-focus-on');
*/
function resizeFocuser(selector, offset = 0) {
const element = document.querySelector(selector.replaceAll(':', '\\:'));
if (!element) return;
window.addEventListener('resize', () => {
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - offset;
window.scrollTo({
top: offsetPosition,
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment