Skip to content

Instantly share code, notes, and snippets.

@haipham
Forked from enwin/sticky-focus.js
Created May 17, 2022 13:11
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 haipham/0de6b44ed677aeb4d2bc923f9540a44c to your computer and use it in GitHub Desktop.
Save haipham/0de6b44ed677aeb4d2bc923f9540a44c to your computer and use it in GitHub Desktop.
Detect and change the scroll position when a focused element is under a sticky element
// sticky element
var stickyHeader = document.querySelector( '.intro-banner' );
function handleFocus( e ){
// don't try to change the scroll if the focused element is in the sticky element
if( stickyHeader.contains( e.target )){
return;
}
// quick & dirty client height on each focus
// get the sticky element's height (can be done on mediaquery change instead of each time)
var headerHeight = stickyHeader.clientHeight;
// get the screen position of the focused element
var focusTop = e.target.getBoundingClientRect().top;
// get the current scroll
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// scroll when the focused element is under the sticky element
if( focusTop < headerHeight ){
document.documentElement.scrollTop = document.body.scrollTop = scrollTop - headerHeight;
}
}
document.body.addEventListener( 'focus', handleFocus, true );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment