3

I am trying to mute / unmute my video. But to start with, it looks like I am not able to select my video. Tried tutorial examples and answers to similar questions but they all point to the same way of selecting the video. Please advice what is wrong here. Thank you.

<!-- HTML -->
<button id="enableMute" onclick="enableMute()" type="button">Mute</button>
<button id="disableMute" type="button">Enable</button>
<button id="checkMute" type="button">Status</button><br>

<video id="myVideo" width="320" height="176" autoplay loop muted>
    <source src="video/trailer.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>

<!-- JS -->
$(function() {
    // seems not being selected. Tried without hash and same result. 
    var vid = $("#myVideo"); 

    //alert works but clearly nothing happening with mute controls
    $("#enableMute").click(function(){
        alert("enableMute");
        vid.muted = true;
        vid.volume = 1.0;
    });

    //alert works but clearly nothing happening with mute controls
    $("#disableMute").click(function(){
        alert("disableMute");
        vid.muted = false;
        vid.volume = 1.0;
    });

    //if i click this button first, the alert is "alert undefined"
    $("#checkMute").click(function(){
        alert('alert: ' + vid.muted); 
    });
}); 
user3050832
  • 169
  • 1
  • 11

1 Answers1

1

The video is being selected and put into the variable. Using .muted won't work and you need to use jQuery's .prop() function as I found out in this question. This should work:

HTML

<button id="enableMute" onclick="enableMute()" type="button">Mute</button>
<button id="disableMute" type="button">Enable</button>
<button id="checkMute" type="button">Status</button><br>

<video id="myVideo" width="320" height="176" autoplay loop muted>
    <source src="video/trailer.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>

JavaScript

$(function() {
  // Video is being selected
  var vid = $("#myVideo");

  $("#enableMute").click(function() {
    alert("enableMute");
    vid.prop('muted', true);
    vid.prop('volume', 1.0);
  });

  $("#disableMute").click(function() {
    alert("disableMute");
    vid.prop('muted', false);
    vid.prop('volume', 1.0);
  });

  $("#checkMute").click(function() {
    alert('alert: ' + vid.prop('muted'));
  });
});

To see it in action with a sample video, go to this link.

Maytha8
  • 846
  • 1
  • 8
  • 26