Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio on scroll

I'm doing a website with the skrollr plugin and I'm almost done with the pictures and scrolling itself, so I'm trying to add the audio now, but I can't seem to make the audio start and stop when I want it to. This is the script I am currently working with:

<script>

$(window).scroll(function() {
    var height = $(document).height() - $(window).height();
var scroll = $(window).scrollTop();  
      var audioElm = $('#soundTour').get(0);
    audioElm.play();
    audioElm.volume = 1 - $(window).scrollTop()/height;
    console.log(audioElm.volume);
});
</script>

This makes my audio start as soon as the website is loaded and fade out across the span of the entire website, so when you've scrolled to the bottom, it's completely silent. I've tried messing with the "height" variable in the script, but to no avail. The sound always ends up heavily lowered, but still faintly playing in the background. Is there a way to make it shut up at a certain scroll point? For example, make the audio play at $(window).scrollTop() = 500 and stop at $(window).scrollTop() = 3000?

like image 763
Milad Emadi Avatar asked Oct 19 '22 10:10

Milad Emadi


1 Answers

var playing = false;
var audioElm = $('#soundTour').get(0);
$(window).scroll(function() {
  var pageScroll = $(window).scrollTop();
  if(!playing && pageScroll > 500 && pageScroll < 3000){
    audioElm.play();
    playing = true;
  }else if(pageScroll > 3000 || pageScroll < 500){
    audioElm.pause();
    playing = false;
  }
});

You need to add some conditions. (I define the variables outside for performance matters, as jQuery scroll has really bad performance, that gets even worse on phones).

Pen: http://codepen.io/vandervals/pen/KpWzVJ

like image 55
Vandervals Avatar answered Oct 22 '22 00:10

Vandervals