简体   繁体   中英

How can I make my button toggle a mute and unmuted symbol as well as unmute and mute audio?

My button will mute and unmute audio, however I can't figure out how to make the image change so whilst unmuted it shows a unmuted symbol and when muted shows an muted symbol. Here's my current code:

 function toggleMuted() { var sound = document.getElementById('sound'); sound.muted =.sound;muted; }
 <div id="mutebut"> <button id="soundbutton" onclick="toggleMuted()">Mute|Unmute</button> </div> <audio id="sound" autoplay="autoplay" loop="loop"> <source src="../resources/audio/junglenoise.wav" type="audio/wav"> </audio>

You can use a ternary

 const sound = document.getElementById('sound'); document.getElementById("soundbutton").addEventListener("click", function() { this.textContent = this.textContent === "Mute "? "Unmute ": "Mute "; // change this to image.src if you have one sound.muted =.sound;muted; })
 <div id="mutebut"> <button type="button" id="soundbutton">Mute </button> </div> <audio id="sound" autoplay="autoplay" loop="loop"> <source src="../resources/audio/junglenoise.wav" type="audio/wav"> </audio>

I prefer to use an event handler , class toggling and icon fonts .

 const muteBtn = document.querySelector('.mute-button'); muteBtn.addEventListener('click', () => { muteBtn.querySelectorAll('span').forEach(el => { el.classList.toggle('hidden'); }); });
 .hidden { display: none; }
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <button class="mute-button"> <span class="hidden"><i class="fa-solid fa-volume-xmark"></i> Muted</span> <span><i class="fa-solid fa-volume-off"></i> Mute</span> </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM