audiovideocontrollermute

Change video onclick function from play/pause to mute/unmute


I have a header video and bydefault it needs to be muted so it can be autoplayed on all browsers, I want to hide all video controles at the same time give options for users to mute and unmute the video as they wany, I want to change onClick funtion of the video from Play/Pause to be Mute/Unmute, How can I do this?

I tried to tweek some solutions from Stack but I couldn't figure out how to do it.


Solution

  • You can use the muted attribute to toggle the audio of the video, as long as your video is muted by default.

    const video = document.getElementById('myVideo');
    
    video.addEventListener('click', () => {
        video.muted = !video.muted;
    });
    

    It's also possible to do it directly using the html onclick event attribute without using a separate script:

    <video id="myVideo" width="320" height="240" autoplay muted onclick="event.target.muted = !event.target.muted">
            <source src="sample.mp4" type="video/mp4">
    </video>