Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Muted video fails to autoplay when inserted into HTML via Javascript

I am trying to insert an HTML5 <video> element through Javascript, but it fails to autoplay despite it being muted.

Background Context

I would like to transfer all of my gif assets over to an mp4 format. Likewise, I would like the HTML video to emulate a gif. It should include the following properties:

  • Be muted
  • Autoplays as soon as the webpage loads
  • Loop indefinitely
  • Plays in line

I am currently on Chrome 100.

What I've Tried

Relevant code is held within this codepen. I want to add the HTML video dynamically through javascript. However this fails to autoplay even though both autoplay and muted attributes are specified.

However, if I have the video element with the same attributes directly written in my HTML, the autoplay functionality works just fine.


How do I insert the video with JS and get it to autoplay?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think you could rather set attributes like this :

const anchor = document.querySelector('#anchor');
const vid = document.createElement('video');
anchor.appendChild(vid);
vid.autoplay = true;
vid.loop = true;
vid.muted = true;
vid.playsinline = true;
vid.src = 'https://www.w3schools.com/html/mov_bbb.mp4';

Try to make these modifications. If it still not working, you could add this inline after above code :

vid.play()
about 4 years ago · Juan Pablo Isaza Report

0

It looks like Chrome is ignoring the muted attribute set before the media has loaded. The video is auto-played if the muted attribute is set when the media is loaded and can be played, which can be checked with the canplay event listener.

vid.oncanplay = () => {
    vid.muted = true;
    vid.play();
}

With this, you can ignore setting the autoplay and muted attributes initially.

const anchor = document.querySelector('#anchor');
const vid = document.createElement('video');
vid.setAttribute('loop', '');
vid.setAttribute('src', 'https://www.w3schools.com/html/mov_bbb.mp4');
vid.oncanplay = () => {
    vid.muted = true;
    vid.play();
}
anchor.appendChild(vid);
body {
  background-color: black;
  color: white;
}
<div id="anchor"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!