0

I am using the following script to with the audio controls class="box follow-scroll" to make it float while the page is scrolling. But I was wondering if it possible to make it float only while the audio is in either play or pause mode? If it stopped it didn't start, it stays where it is.

$(window).load(function(){

    (function($) {
        var element = $('.follow-scroll'),
            originalY = element.offset().top;

        var topMargin = 20;
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
            }, 300);
        });
    })(jQuery);

});

The html:

<audio controls class="box follow-scroll">
<source src="http://techslides.com/demos/samples/sample.ogg" type="audio/ogg">
<source src="http://techslides.com/demos/samples/sample.mp3" type="audio/mpeg">
</audio>
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Mike
  • 2,051
  • 4
  • 28
  • 46

1 Answers1

0

Add two eventlisteners to your audio element. One that starts floating when your audio is playing, and one that resets your audio element when it is paused. In the following example the stopFloating() resets your audio element by setting var scrollTop = 0; to zero. You can of course further tune this function.

Something like:

var element = $('.follow-scroll'), originalY = element.offset().top;

var topMargin = 20;
element.css('position', 'relative');

element[0].addEventListener("playing", function() {
    startFloating();
});

element[0].addEventListener("pause", function() {
    stopFloating();
});


function startFloating () {
    $(window).on('scroll', function(event) {

        var scrollTop = $(window).scrollTop();

        element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
        }, 300);    
    });
}

// Reset your element
function stopFloating () {
    $(window).on('scroll', function(event) {

        var scrollTop = 0;

        element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
        }, 300);    
    });
}
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85