I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to function properly. I've searched for solutions on CodePen, but haven't had any luck. I'm really hoping someone can offer some assistance. At one point, I did manage to get it working, but the pause function was not working correctly, so I had to rewrite the code.
Here is the HTML snippet related to the music button:
<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>
<!--<a onclick="musicPlay()"><img src="music2.png" width="65px"></a>-->
</li>
</ul>
Here is the CSS code related to styling the music button:
#music-button-container,
#play-pause {
cursor: pointer;
height: 50px;
width: 70px;
padding: 12px 18px;
background-repeat: no-repeat;
background-position: center;
background-size: 50px;
}
.play {
background-image: url(./music2.png);
}
.pause {
background-image: url(./equalizer.png) !important;
}
Lastly, here is the JavaScript code that I believe is causing the issue:
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;
}