Search code examples
javascriptvideomute

Video Mute and unmute button


I'm trying to add a mute/unmute button to a fullscreen background video. I used a piece of javascript which is widely published including on stackoverflow (HTML Video mute button). Unfortunately, this defaults to mute. No matter what I try I can't get to default to unmute. Clearly I'm a js newbie.

<video class="video" autoplay loop>
    <source src="video.mp4" type="video/mp4">
</video>
<button class="mute-video unmute-video"></button>
$("video").prop('muted', true);

$(".mute-video").click(function () {
    if ($("video").prop('muted')) {
        $("video").prop('muted', false);
        $(this).addClass('unmute-video'); // changing icon for button

    } else {
        $("video").prop('muted', true);
        $(this).removeClass('unmute-video'); // changing icon for button
    }
    console.log($("video").prop('muted'))
});

Solution

  • Maybe you need to wait for the video to be ready in order to access its properties. Try using oncanplay event:

    $("video").oncanplay = function() {
        $("video").prop('muted', true);
    };
    
    $(".mute-video").click(function () {
        if ($("video").prop('muted')) {
            $("video").prop('muted', false);
            $(this).addClass('unmute-video'); // changing icon for button
    
        } else {
            $("video").prop('muted', true);
            $(this).removeClass('unmute-video'); // changing icon for button
        }
        console.log($("video").prop('muted'))
    });