skip to Main Content

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

3

Answers


  1. You need to do an action inside your function for that. Try to get the element (add an ID) and change the class of the i element

    Login or Signup to reply.
  2. you can use classList, add() and remove():

    let pause = true;
    
    document.getElementById("btn_playPause").addEventListener("click", () => {
      let icon = document.querySelector("i");
      if (pause) {
        icon.classList.add("fa-pause");
        icon.classList.remove("fa-music");
        pause = false;
      } else {
        icon.classList.add("fa-music");
        icon.classList.remove("fa-pause");
        pause = true;
      }
    });
    

    the second way is that you can use className:

    document.querySelector("i").className = `fa ${pause ? "fa-pause" : "fa-music"}`;
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search