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>
<!--<a onclick="musicPlay()"><img src="music2.png" width="65px"></a>-->
</li>
</ul>
This is the CSS code:
#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;
}
Finally, the 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;
}