JQuery scrollTop () as a 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 displayed. When you scroll the next section, the audio player stops after scrolling 1400, but I need this to be relative. How to make 1400 percent (50%)

+5
source share
2 answers

It is possible - any arithmetic will do the job. The trick is to get the page height using $(document).height() . If you mean the height of the viewport, then you will need to use $(window).height() .

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

Try using 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); }); 
+1
source

Source: https://habr.com/ru/post/1211536/


All Articles