Skip to content

Instantly share code, notes, and snippets.

@lionelB
Forked from enwin/sticky-focus.js
Created June 19, 2018 15:22
Show Gist options
  • Select an option

  • Save lionelB/288e5dd5747adbd0ab8afee4af592bd2 to your computer and use it in GitHub Desktop.

Select an option

Save lionelB/288e5dd5747adbd0ab8afee4af592bd2 to your computer and use it in GitHub Desktop.

Revisions

  1. @enwin enwin created this gist Jun 13, 2018.
    24 changes: 24 additions & 0 deletions sticky-focus.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    // 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.offsetTop;
    // get the current scroll
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

    // scroll when the focused element is under the sticky element
    if( focusTop === scrollTop || ( focusTop > scrollTop && focusTop < (scrollTop + headerHeight) ) ){
    document.documentElement.scrollTop = document.body.scrollTop = focusTop - headerHeight;
    }
    }

    document.body.addEventListener( 'focus', handleFocus, true );