skip to Main Content

There is such a code. I need to execute the js code when the page is scrolled by 50% 1 time.
But my code is executed every time I move.
Help me fix it

document.addEventListener("scroll", function() {
const height = window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)

if ( height > 0.5 ) {
console.log('End 50');

}
})

I tried return 0; and break

2

Answers


  1. Chosen as BEST ANSWER

    Thanks! Although this part doesn't work correctly for me, I was able to write working code for myself.:

    <script>   
    
    document.addEventListener('scroll', halfPageScroll);
    function halfPageScroll(e) {
    const height = window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)
    
    if ( height > 0.5 ) {
    console.log('End 50');
     document.removeEventListener('scroll', halfPageScroll);
    }
    }
    </script>
    

  2. First, get the page height:

    var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, 
                           document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);
    

    Now, get 50% of it:

    var halfPage = pageHeight / 50;
    

    Now listen to the scroll event:

    document.addEventListener('scroll', halfPageScroll);
    function halfPageScroll(e) {
        if(window.scrollY >= halfPage) {
            alert('50% scrolled');
    
            // Remove event listener so that this only fires the first time a user scrolls 50% of the page
            document.removeEventListener('scroll', halfPageScroll);
        }
    }
    

    Note: This approach may not work if the page has dynamically loaded content. Because the page height can increase as the user scrolls down the page, so it is difficult to determine the full page height.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search