0

So I was wondering if I could make it so that the video on my website starts playing when the user scrolls into the view of it. I've tried quite a few things such as scrollspy and some other code I found on this website, but none of it works, I always get the same result: the website messes up completely, pictures move out of sight, sections change places or disappear and it's not very fun.

This is the current JS code for our MediaElementPlayer:

if ($('.video-promo').length ) {
    var player_promo = new MediaElementPlayer('.video-promo', {
        videoWidth: '100%',
        videoHeight: '100%',
        loop: false,
        alwaysShowControls: true,
        features: [],
    });

    player_promo.play();
}

And the HTML:

        <section class="promo motions">
        <video class="video-promo">
                <source type="video/mp4" src="assets/video/demo.mp4" />
        </video>
      <div class="video-overlay"></div>
    </section>

Cheers for any help! :D

1 Answers1

0

Check out Dan's answer on: How to tell if a DOM element is visible in the current viewport?

In short you can add:

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() */
    );
}

function elementVisibilityMayChange () {
    return function () {
        if ( isElementInViewport($('.video-promo')[0]) ) {
            player_promo.play();
        }
    }
}

var handler = elementVisibilityMayChange();

$(window).on('DOMContentLoaded load resize scroll', handler); 
Community
  • 1
  • 1
Sgoldy
  • 726
  • 3
  • 14
  • Cheers! Where should I add this? – Aria Roberts Feb 18 '14 at 10:11
  • Anywhere on the page with the video player would do. – Sgoldy Feb 18 '14 at 10:24
  • I did exactly that, but it still messed up the page. Example: http://i.imgur.com/dDdMIjz.png & http://i.imgur.com/xkpRB5M.png (that's the video - it usually takes up that whole area. I'd show more, but I don't really want to show too much of my unfinished website :3 – Aria Roberts Feb 18 '14 at 10:40
  • Alright, so I got it to stop messing up the page, but it still doesn't play the video when I scroll onto it. – Aria Roberts Feb 18 '14 at 10:56