2

I found this script that'll automatically play a video when the element is in the viewport

$(window).scroll(function() {
    $('#youtube-player-container').each(function(){
    var imagePos = $(this).offset().top;

    var topOfWindow = $(window).scrollTop();
        if (imagePos < topOfWindow+600) {
            $('#youtube-player-container').tubeplayer("play");
        }
    });
});

This works great, but I'd also like to pause the video again when it is no longer on screen. What would I need to edit/add to achieve this?

EDIT: I know there is an action 'tubeplayer("pause") available, I just don't know how to activate it.

user48745
  • 97
  • 6

2 Answers2

1

Try this and let me know if it works:

//this version uses a class instead of an ID
$(window).scroll(function() {
$('.youtube-player-container').each(function(){
var imagePos = $(this).offset().top;

var topOfWindow = $(window).scrollTop();
    if (imagePos < topOfWindow+600) {
        $(this).tubeplayer("play");
    }else{
        $(this).tubeplayer("pause");
    }
});
});

or

//use this one if you are using an ID, but double check this because I wrote it in a hurry.
$(window).scroll(function() {
var videoPos = $('#youtube-player-container')offset().top;
var topOfWindow = $(window).scrollTop();
    if (videoPos < topOfWindow+600) {
        $('#youtube-player-container').tubeplayer("play");
    }else{
        $('#youtube-player-container').tubeplayer("pause");
    }
});
//double check my blocks, I might not have kept them balanced. I was in a hurry.
TecBrat
  • 3,265
  • 2
  • 24
  • 39
  • The reson I changed the selector to `this` is to prevent all videos on the page from starting and stopping at once. – TecBrat Mar 21 '14 at 13:10
  • 1
    iterating through ids is a bad practice, I suppose the op meant to use a class – syd619 Mar 21 '14 at 13:13
  • This did not work. It pauses again when I scroll UP, but if I scroll further down it keeps playing. – user48745 Mar 21 '14 at 13:52
1

A very nice function to determine if your element is in the viewport Link

function isElementInViewport (el) {
    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

in total:

$(window).scroll(function(){

    $('.youtube-player-container').each(function(){
        var $this = $(this);
        var el = $this.get(0);
        if (isElementInViewport(el)) {
            $this.tubeplayer("play");
        } else {
            $this.tubeplayer("stop");
        }       
    })

})

PS: id is a uniquer selector I assume you meant to type '.youtube-player-container'

Community
  • 1
  • 1
syd619
  • 2,952
  • 4
  • 39
  • 75