<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%)
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();
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With