Play/pause button HTML/CSS/JS

Hi,

I am working on a project, and I am trying to create a music button in the navigation bar. When you click on it, a song plays and clicking on it once more pauses it.

I have tried several versions, but unsure why they aren’t working. Had a look on codePen for ideas, but still no luck. Hoping someone is able to help.

I managed it to work at one point, but it didn’t pause at all, so I re-wrote the code.

This is the relevant HTMl code:
<ul> <li class="nav-item nohover"> <audio id="music-button"> <source src="Zara%20Larsson%20Lush%20Life%20Lyrics.mp3" preload="auto" type="audio/mpeg"/> </audio> <div id="music-button-container"> <div id="play-pause" class="play"></div> </div> </li> </ul>

This is my JavaScript code, where I think the issue lies.

var music = document.getElementById('music-button');
 var controlButton = document.getElementById('play-pause');

 function musicPlay() {
    if (music.paused) {
    music.play();
    controlButton.className = "pause";
     } else {
       music.pause();
       controlButton.className = "play";
     }
   }
 
 controlButton.addEventListener("click", musicPlay);
 music.addEventListener("ended", function () {
 controlButton.className = "play";
 });

/* This is what I have tried as well*/

 document.querySelector(".play-pause").addEventListener("click",
 function() {
 if (music.paused) {
    music.play();
  } else {
    music.pause();
  }
 });

 function musicPlay() {
   var music = document.getElementsById("music-button");
   return music.paused ? music.play() : music.pause();
  }

 var isPlaying = false;

 function musicPlay() {
  return music.paused ? music.play() : music.pause();
 }
   music.onplaying = function() {
   isPlaying = true;
 };
 music.onpause = function () {
   isPlaying = false;
 }

It would be better if you put this in something like codepen so we can see everything you have done and test it for ourselves.

Hi, yes i can put it into codepen.

I worked out that putting the JS code at the bottom of closing body tag helped it to work.

Here’s the code pen for the code: https://codepen.io/mariabcodes/pen/OJBKmeO

I would prefer for the JS code to be within JS page, but it seems that I can’t get away from that

Sorry, I’m not seeing a play button in your codepen.

The audio source you have now is not going to work on Codepen. Where does the file exist in relation to the page?

Zara%20Larsson%20Lush%20Life%20Lyrics.mp3

If I replace the source with something else it works.

https://www.bensound.com/bensound-music/bensound-moose.mp3


We can’t see the play button because you didn’t give the link any content. Also, you should prefer a button when you can for this.

Also, you have an extra closing </li> in your HTML.