Auto start/play HTML5 video using javascript to avoid use of autoplay attribute

937 Views Asked by At

What I need: a script that will trigger all html5 videos on a page with the same class to play--once the page is loaded--because the html5 autoplay attribute is off limits.

I'm a javascript noob. I've written the script below to fix an issue where autoplay breaks on an html5 video because of a conflict with [skel.js] (https://github.com/n33/skel.old).

I can't write javascript from scratch, so I'm quite ignorant as to what is happening in this script; but, it does what I need it to do on my site. However, I bet it's written poorly or inefficiently. For example, I currently have a separate script for each video/class. I know it would be smarter to call all videos with the same class, but I don't know how. I'd love to know if there is extraneous or bad code here and if there is a better solution to get these videos to autoplay on page load?

Here is the code I'm using:

<script><!-- hack to fix html5 autoplay break when using skel.js-->
    startplaying();
    function startplaying(time) {
        var run = setInterval(function() { $('.video1')[0].play(); }, 2000);
    }
</script>

Here is my complete test code:

<!DOCTYPE HTML>
<html>
<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<script src="js/jquery.min.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-layers.min.js"></script>

</head>
<body>

<video class="video1" width="100%" controls loop><!-- can't use autoplay becuase of a bug!-->
    <source src="http://coldriverfurniture.com/_TEST/images/about-water-powered-tenoning-machine.mp4" type="video/mp4">
    <source src="http://coldriverfurniture.com/_TEST/images/about-water-powered-tenoning-machine.ogg" type="video/ogg">
    Your browser does not support this video.
</video>

<video class="video2" width="100%" controls loop><!-- can't use autoplay becuase of a bug!-->
    <source src="http://coldriverfurniture.com/_TEST/images/about-water-powered-tenoning-machine.mp4" type="video/mp4">
    <source src="http://coldriverfurniture.com/_TEST/images/about-water-powered-tenoning-machine.ogg" type="video/ogg">
    Your browser does not support this video.
</video>

<script><!-- hack to fix html5 autoplay break when using skel.js-->
    startplaying();
    function startplaying(time) {
        var run = setInterval(function() { $('.video1')[0].play(); }, 2000);
    }
</script>

<script>
    startplaying();
    function startplaying(time) {
        var run = setInterval(function() { $('.video2')[0].play(); }, 2000);
    }
</script>

<script src="js/init.js"></script>

</body>
</html>

Thanks!

0

There are 0 best solutions below