Skip to content

Instantly share code, notes, and snippets.

@vichfs
Created October 3, 2024 10:46
Show Gist options
  • Save vichfs/468a5baeb4241de0fd497b544f7c2104 to your computer and use it in GitHub Desktop.
Save vichfs/468a5baeb4241de0fd497b544f7c2104 to your computer and use it in GitHub Desktop.
JS Function to Scroll to Focused Element
function scrollToFocusedElement() {
const focusedElement = document.activeElement;
if (focusedElement) {
const rect = focusedElement.getBoundingClientRect();
const scrollTop = window.scrollY || document.documentElement.scrollTop;
const elementTop = rect.top + scrollTop;
window.scrollTo({
top: elementTop,
behavior: 'smooth'
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment