Autoplaying HTML5 Video In Chrome

Published on
-
1 min read

Whilst working on the new look for my website, I wanted to replace areas where I previously used low-grade animated GIF's for the more modern HTML5 video. Currently, the only place I use HTML5 video is on my 404 page as a light-hearted reference to one of the many memorable quotes that only fans of the early Star Trek films will understand. These are the films I still hold in very high regard, something the recent "kelvin timeline" films are missing. Anyway, back to the post in hand...

Based on Chrome's new policies introduced in April 2018 I was always under the impression that as long as the video is muted, this won't hinder in any way the autoplay functionality. But for the life of me, mt HTML5 video did not autoplay, even though all worked as intended in other browsers such as Firefox.

You can work around Chrome's restrictions through JavaScript.

Code

The HTML is as simple as adding your HTML5 video.

<video id="my-video" autoplay muted loop playsinline>
     <source src="/enterprise-destruction.mp4" type="video/mp4" />
</video>

All we need to do is target our video and tell it to play automatically. I have added a timeout to the script just to ensure the video has enough time to render on the page before our script can do its thing.

var myVideo = $("#my-video");

setTimeout(function () {
    myVideo.muted = true;
    myVideo.play();
}, 100);

It's worth noting that I don't generally write much about front-end approaches (excluding JavaScript) as I am first and foremost a backend developer. So this might not be the most ideal solution and appreciate any feedback.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.