Search code examples
htmlcssbuttontoggle

Change font awesome icon when clicked button


I'm using this code to play/pause background audio.

<div class="music-box">
   <audio id="losAudio" src="images/honcayeu.mp3"></audio>
      <button id="btn_playPause">
         <i class="fa fa-music"></i>
      </button>
</div>
var losAudio = document.getElementById("losAudio");
function losAudio_playPause() {
   var isPaused = losAudio.paused;
   losAudio[isPaused ? "play" : "pause"]();
}
document.getElementById("btn_playPause").addEventListener("click",losAudio_playPause);

But now i want when clicked on button, the icon will be change to fa-pause icon. Can tell me a simple solution ? THanks


Solution

  • To change the icon of the button from fa-music to fa-pause when the audio is playing, you can modify your losAudio_playPause function to update the button icon accordingly.

    Try This :

    var losAudio = document.getElementById("losAudio");
    var playPauseButton = document.getElementById("btn_playPause");
    
    function losAudio_playPause() {
        var isPaused = losAudio.paused;
        losAudio[isPaused ? "play" : "pause"]();
        playPauseButton.innerHTML = '<i class="fa ' + (isPaused ? 'fa-music' : 'fa-pause') + '"></i>';
    }
    
    playPauseButton.addEventListener("click", losAudio_playPause);
    
    

    What this does is it checks whether the audio is currently paused or playing, and sets the button icon to fa-music or fa-pause respectively using a ternary operator. The innerHTML property is then used to update the button's content with the new icon.