Created
October 3, 2024 10:46
-
-
Save vichfs/468a5baeb4241de0fd497b544f7c2104 to your computer and use it in GitHub Desktop.
JS Function to Scroll to Focused Element
This file contains hidden or 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
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