Handle HTML5 video autoplay with Javascript

Sometimes we need to autoplay a video using the tag <video> when a user click a button or when a page is loaded.

In this post I will share a simple example how we can achieve that.

// Get the video element
const video = document.getElementById('videoElement');

if (video) {
    // get the tags sources inside the video tag
    const sources = video.getElementsByTagName('source');

    // Add a listener to the tag video when is loaded and play the video
    video.addEventListener('loadeddata', () => video.play(), false)

    /**
     * isMobile is a function to detect if the device is a mobible device or not
     * If is true load the mobile version of teh video via data attribute
     * Else load the Desktop version
     */ 
    isMobile.any()
        ? (sources[0].src = video.getAttribute('data-mobile'))
        : (sources[0].src = video.getAttribute('data-desktop'))

    // load the video added to the source value
    video.load()
}
...
<video class="" id="videoElement" 
    autoplay="autoplay" loop="loop" 
    muted="muted" playsinline 
    data-desktop="video.mp4" 
    data-mobile="video-mobile.mp4">
        <source src="" type="video/mp4">
</video>
...

Is important to have the playsinline attribute in the video tag if not the video wont autoplay on mobile devices

Leave a Reply

Your email address will not be published. Required fields are marked *