Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 video muted attribute not applied using property but applied using setAttribute

I've found a curious inconsistency when working with HTML5 video.

Compare these two code snippets and take a look at the Elements tab in Chrome developer tools

<body>
  <script>
    const video1 = document.createElement('video');
    video1.autoplay = true;
    video1.muted = true;
    document.body.appendChild(video1);

    const video2 = document.createElement('video');
    video2.setAttribute('autoplay', 'autoplay');
    video2.setAttribute('muted', 'muted');
    document.body.appendChild(video2);
  </script>
</body>

For the first video, muted set using a JS object property wasn't set. For the second one, using setAttribute worked and the DOM attribute is set. Interestingly, this is not the case for autoplay where it behaves consistently.

Why is that? Is there another example of an attribute behaving this way? Is there a rule to this? How does one tell which attribute's property behaves which way in JS except for testing?

like image 322
Tomáš Hübelbauer Avatar asked Jan 14 '17 23:01

Tomáš Hübelbauer


People also ask

Which of the following code is correct to play a video in muted mode in HTML?

prop('muted', true);

What attribute can mute audio tags or video tags?

The muted attribute mutes (silences) the audio or video control. To play the media file, click the mute button, or remove the muted attribute.

How do I enable audio on a video in HTML?

If you want to muted the video try muted . If you want to loop the video, add loop attribute as <video src="video/video. mp4" controls autoplay loop></video> .


1 Answers

The attributes are only used to initialize the properties. They do not reflect the current state.

By setting the properties directly, you update the object, but do not affect the dom attributes.

If you set the src of the video (so you can actually see it in action) you will see that the properties have been properly applied

const video1 = document.createElement('video');

video1.src = 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
video1.controls = true;
video1.autoplay = true;
video1.muted = true;

document.body.appendChild(video1);
like image 170
Gabriele Petrioli Avatar answered Sep 29 '22 03:09

Gabriele Petrioli