Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 878
Peyton Gregory Avatar asked Jan 20 '15 18:01

Peyton Gregory


2 Answers

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();
});
like image 78
Terry Avatar answered Sep 30 '22 03:09

Terry


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

});
like image 31
derogab Avatar answered Sep 30 '22 02:09

derogab