Issue
I have a video with a custom mute control button. I would like the icon to change on click. Here is the code I currently have:
<video id="myVideo" loop autoplay muted>
<source src="https://md-testdomein.nl/partyz/wp-content/uploads/2023/12/WEBVERSIE_169_PartyZ_Brandfilm_V8.01.mp4">
</video>
<button id="mute-button" onclick="muteToggle();" type="button">
<i id="mute-button-icon" class="fa fa-volume-up"></i>
</button>
<script>
function muteToggle() {
let vid=document.getElementById("myVideo");
let element = document.getElementById("mute-button-icon");
if(vid.muted){
vid.muted = false;
element.classList.toggle("fa-volume-up");
} else {
vid.muted = true;
element.classList.toggle("fa-volume-off");
}
}
</script>
You can preview the button on site here: https://md-testdomein.nl/partyz/
The button icon does change but the first time I click it the icon disappears, the second time the icon 'fa-volume-off' shows up and the third time the icon 'fa-volume-up' shows up.
The icon 'fa-volume-up' should be shown when the audio is off and the icon 'fa-volume-off' should show when the audio is on.
This should be pretty easy but I can't figure it out. Can someone help me fix it.
Solution
The issue in your code is because you toggle only 1 of the classes. You need to toggle them both so that the old class is removed and the new one gets added.
You can also simplify the logic to mute the video, and improve code quality by moving the event handler binding in to JS instead of in the HTML.
Here's a working example. Note that I only reduced the size of the video so it fits better in the snippet preview.
const vid = document.querySelector('#myVideo');
const muteIcon = document.querySelector('#mute-button-icon');
document.querySelector('#mute-button').addEventListener('click', e => {
vid.muted = !vid.muted;
muteIcon.classList.toggle('fa-volume-up');
muteIcon.classList.toggle('fa-volume-off');
});
video { width: 300px; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<video id="myVideo" loop autoplay muted>
<source src="https://md-testdomein.nl/partyz/wp-content/uploads/2023/12/WEBVERSIE_169_PartyZ_Brandfilm_V8.01.mp4">
</video>
<button id="mute-button" type="button">
<i id="mute-button-icon" class="fa fa-volume-off"></i>
</button>
Answered By - Rory McCrossan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.