Peyton Gregory
Peyton Gregory

Reputation: 147

jQuery scrollTop() position to percentage

<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%)

Upvotes: 9

Views: 18255

Answers (2)

Terry
Terry

Reputation: 66123

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();
});

Upvotes: 8

derogab
derogab

Reputation: 152

Try to use this code:

$(window).on('scroll', function() {
   var st = $(this).scrollTop();
   var wh = $(document).height();

// st : wh = X : 100
// x = (st*100)/wh

var perc = (st*100)/wh

// Your percentage is contained in perc variable

console.log('The percentage is '+perc);

});

Upvotes: 4

Related Questions