Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action when element is off screen again with jQuery?

Tags:

jquery

scroll

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.

like image 403
user48745 Avatar asked Feb 21 '26 13:02

user48745


1 Answers

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'

like image 141
0x_Anakin Avatar answered Feb 24 '26 05:02

0x_Anakin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!