jQuery scrollTop() position to percentage

Peyton Gregory picture Peyton Gregory · Jan 20, 2015 · Viewed 15.1k times · Source
<script>
document.getElementById('listen-btn').addEventListener('click', function() {
    document.getElementById('music-player').play();
});

<script>
    $(window).scroll(function() {
        if($(window).scrollTop() > 1400)
        document.querySelector('#music-player').pause();
    });
</script>

The button starts the audio player and scrolls to the section where the audio player is visible. When you scroll the the next section the audio player stops once you've scrolled 1400 but I need that to be relative. How to I make the 1400 a percentage (50%)

Answer

Terry picture Terry · Jan 20, 2015

That is possible — some arithmetic will do the job. The trick is to retrieve the page height using $(document).height(). If you're referring to the viewport height though, then you will need to use $(window).height().

$(window).scroll(function() {
    if($(window).scrollTop() > $(document).height()*0.5)
    document.querySelector('#music-player').pause();
});