Skip to content

Instantly share code, notes, and snippets.

@jasubal
Last active January 15, 2024 11:05
Show Gist options
  • Select an option

  • Save jasubal/00b2f21c3d175ba56c25047a3b459703 to your computer and use it in GitHub Desktop.

Select an option

Save jasubal/00b2f21c3d175ba56c25047a3b459703 to your computer and use it in GitHub Desktop.

Revisions

  1. jasubal renamed this gist Jan 15, 2024. 1 changed file with 0 additions and 0 deletions.
  2. jasubal revised this gist Jan 15, 2024. No changes.
  3. jasubal created this gist Jan 15, 2024.
    26 changes: 26 additions & 0 deletions scrolldetector-scrolledone.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    let lastScrollTop = 0;
    const $html = document.documentElement;
    $html.classList.add('near-top');

    window.addEventListener('scroll', () => {
    const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const docHeight = Math.max($html.scrollHeight, $html.offsetHeight, $html.clientHeight);
    const scrolledPercentage = ((currentScrollTop + windowHeight) / docHeight) * 100;
    const remainingScroll = 100 - scrolledPercentage;

    // Determine scroll direction and update classes using ternary expressions
    currentScrollTop > lastScrollTop ?
    ($html.classList.add('scrolling-down'), $html.classList.remove('scrolling-up')) :
    ($html.classList.add('scrolling-up'), $html.classList.remove('scrolling-down'));

    // Add or remove class based on scroll position using a ternary expression
    currentScrollTop <= 100 ?
    $html.classList.add('near-top') :
    $html.classList.remove('near-top');

    lastScrollTop = currentScrollTop <= 0 ? 0 : currentScrollTop;

    // Log or use the remainingScroll percentage as needed
    console.log(`Remaining scroll: ${remainingScroll.toFixed(2)}%`);
    });