Marnik Bruyndonckx
Marnik Bruyndonckx

Reputation: 69

Javascript mute/unmute video using image

For some reason, it's just not working.. What am I doing wrong? I want to be able to mute and unmute the video using an image, which is changing whether the video is muted or not.

 function mute() {
            var video = document.getElementById("bgvid");
         if (!video.muted) {
             document.getElementById('muteicon').src = "Images/muteicon.png";
            video.muted;
         }     else {
             document.getElementById('muteicon').src = "Images/soundicon.png";
             video.muted == false;
             }

        }
video#bgvid {
            margin-top: 30px;
            margin-bottom: 60px;

            width: 1280px; height: 720px;


            background-size: cover;

        }
        video { display: block; }
<video autoplay loop id="bgvid">
        <source src="newyork.mp4" type="video/mp4">
    </video>
    <br><br>
    <img alt="mute icon" src="Images/soundicon.png" id="muteicon" onclick="mute()">
    <script>
      </script>

Upvotes: 2

Views: 3628

Answers (2)

Bucket
Bucket

Reputation: 7521

You are not setting the muted property to true when you are trying to mute the video.

if (!video.muted) {
    document.getElementById('muteicon').src = "Images/muteicon.png";
    video.muted = true; // you need to assign this value to true
} else { ... }

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

You have to use the assign(=) operator instead of the equality(==) operator:

function mute() {
    var video = document.getElementById("bgvid");

    if (!video.muted) {
        document.getElementById('muteicon').src = "Images/muteicon.png";
        // video.muted <- not assigned to true
        video.muted = true;
    } else {
        document.getElementById('muteicon').src = "Images/soundicon.png";
        // video.muted == false <- wrong use of equality operator
        video.muted = false;
    }
}

And you can't tell the API to set a property to true just by calling it as you made:

video.muted

You have to assign the property to a value:

video.muted = true

Upvotes: 3

Related Questions