I'm using a HTML5 audio tag to play some background music, and I would like the music to pause when the user scrolls past a certain point, and start again when the user scrolls back to the top... Is this possible?
Thanks in advance!
I'm using a HTML5 audio tag to play some background music, and I would like the music to pause when the user scrolls past a certain point, and start again when the user scrolls back to the top... Is this possible?
Thanks in advance!
The following example (plain javascript, no jQuery) pauses the audio if you scrolls the scrollbar 350px down (and plays it again when you get back to the top);
window.addEventListener("scroll", myFunction);
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("player").pause();
} else {
document.getElementById("player").play();
}
}
body {
background: tomato;
}
<audio controls autoplay loop id=player>
<source src="http://www.youtube.com/audiolibrary_download?vid=7fad087239069cd4" type="audio/mpeg">
</audio>
<p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p>
you can bind to the scroll
event to the window and trigger a foreach for $('video')
and call pause
method when the limit and play
when to offset is 0
$(window).on('scroll',function(e){
if (document.body.scrollTop === 0) $('video').forEach(function(){this.play()});
if (document.body.scrollTop > 100) $('video').forEach(function(){this.pause()});
})