autoplay mediaelement player when visible

2.1k views Asked by At

I have a wordpress site that uses the native player, mediaelement to display videos. I'm trying to add some code to autoplay the videos when visible, pause when off the screen. I have been working with a piece of code from my previous question here (using the isInViewport JQuery plugin), but the play/pause events here don't seem to trigger the mediaelement player. I am able to detect when each of the videos are visible and print to the console using the scroll function here. From what I've read I need to initialize the mediaelement player before calling the play/pause function, but I get an error: "Uncaught TypeError: Cannot read property 'player' of undefined" with each scroll where the video is visible.

JQUERY:

$(function() {
    $(window).scroll(function() {
        $('.wp-video-shortcode').each(function() {
            var str = $(this).attr('id');
            var arr = str.split('-');
            typecheck = arr[0];
            if ($(this).is(":in-viewport") && typecheck == "video") {
                var video = new MediaElementPlayer($(this).attr('id'), {
                    success: function(mediaElement) {
                        $(this).attr('id')[0].player.pause(); 
                        console.log($(this).attr('id') + 'video is playing');

                    }
                });

                //$(this).[0].play();
            } else {
                //$(this).[0].pause();
            }

        });
    });
});

HTML:

<video class="wp-video-shortcode" id="video-1115-1" width="792" height="470" poster="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.jpg" loop="1" preload="none" controls="controls">
<source type="video/mp4" src="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.mp4?_=1" /> 
<source type="video/webm" src="http://cdn.ultrasoundoftheweek.com/post_files/uotw16.1.webm?_=1" /> 
</video>
1

There are 1 answers

0
UltrasoundJelly On

For anyone else struggling with this, here is my solution. (isInViewport and JQuery reference above this JQ include). Works on Safari/Chrome/FF newest versions. Doesn't work for mobile. I going to work on a media query and coding something separate for android.

$(function() {
    $(window).scroll(function() {
        $('.wp-video-shortcode').each(function() {
            var str = $(this).attr('id');
            var arr = str.split('_');
            typecheck = arr[0];
            if ($(this).is(":in-viewport( 400 )") && typecheck == "mep") {
                    mejs.players[$(this).attr('id')].media.play();
                    console.log($(this).attr('id') + 'video is playing');
            } else if (typecheck == "mep") {
                    mejs.players[$(this).attr('id')].media.stop();
            }
        });
    });
});