1

Trying to mute video using attr but it doesn't work.

HTML

 <video autoplay muted class='preview-video'>
       <source src='file.mp4' type='video/mp4'>
 </video>

jQuery

function volumeToggle(button) {
    var muted = $(".preview-video").attr("muted");
    $(".preview-video").attr("muted", !muted)
}

However, when I try prop() instead of attr() it works. Can someone explain in detail the reason behind it?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0

You need to toggle the muted property of the video element, not the attribute. Try this:

let $vid = $('.preview-video');

$('button').on('click', function() {
  $vid.prop('muted', (i, m) => !m);
});
video {
  width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Toggle Mute</button>
<video autoplay muted class='preview-video'>
  <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339