typicalnoob
typicalnoob

Reputation: 11

Music player plays all with the same id

Im trying to make a music player where, when the user click on the button, the overlayed image, will change the image to stop.png and play the song. When the user click it again it will change the image to play.png and stop playing song.

<audio id="myAudio">
  <source src="http://www.w3schools.com/jsref/horse.ogg" type="audio/ogg">
  <source src="http://www.w3schools.com/jsref/hors.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
 </audio>
 <script>
function plaYer() {
    var image = document.getElementById('myImage');
    var x = document.getElementById("myAudio"); 

    if (image.src.match("play")) {
        image.src = "stop.png";
         x.play(); 
    } else {
        image.src = "play.png";
        x.pause(); 
    }
}
</script>
<button id="song"  
style="color: white; background-image: url('cover100.jpg'); border: none; outline: none; display:block;
width:100px;
height:100px;">
<img id="myImage" onclick="plaYer()" src="play.png" width="100" height="100">
</button>

My problem is, when I try to create 2 music player the other music player doesnt work. Can someone help me ?

Upvotes: 1

Views: 60

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

IDs have to be unique. If you want to reuse your function, you cannot hardcode the IDs in it. Since you use inline event handlers, you already have access to the image element. Pass that information, plus the ID of the corresponding <audio> element to your function:

function plaYer(image, audioID) {
  var x = document.getElementById(audioID);
  // rest of your code ...
}

// HTML

<img id="myImage" onclick="plaYer(this, 'myAudio')" ... />

I recommend to read the excellent articles on quirksmode.org to learn more about event handling.

Upvotes: 2

Related Questions