user2202031
user2202031

Reputation: 25

Clicking multiple play buttons and playing the corresponding songs

Javascript:

function Start1 ()
{
    var audie = document.getElementById("myAudio");
    audie.src = ("RWY.mp3");
    audie.play();
}

function Start2 ()
{
    var audie = document.getElementById("myAudio");
    audie.src = ("EL.mp3");
    audie.play();

HTML

<img src="images/play.png" alt="Play Button width="37" height="30" 
onclick="Start1()">

I'm trying to select an image and as soon as that image is clicked a song plays according to the file described in the element.

Upvotes: 0

Views: 1650

Answers (2)

Sachin
Sachin

Reputation: 40970

May be I didn't get you problem but Why are you making separate function for each image or audio. You can do it using single function as well by just passing the source of audio file like this

function Start (audioFile)
{
    var audie = document.getElementById("myAudio");
    audie.src = audioFile;
    audie.play();
}

Markup:

<img src="images/play.png" alt="Play Button width="37" height="30" onclick="Start('RWY.mp3')">

<img src="images/play.png" alt="Play Button width="37" height="30" onclick="Start('EL.mp3')">

Update:

function StartOrStop(audioFile)
  {
    var audie = document.getElementById("myAudio");
    audie.src = audioFile;
    if(audie.paused==false)
     {
        audie.Paused();
     }
     else
     {
       audie.play();
     }
  }

Upvotes: 1

Denis O.
Denis O.

Reputation: 1850

Try to avoid having many different functions for the same purpose. You can use jQuery to make your code short and very simple.

$(document).ready(function() { // starting our code when document is loaded
    $('.playbtn').click(function() { // attaching this code to click event of any html element having _playbtn_ class
        $(this).data('song'); // getting song name from _data_ container of clicked element $(this)
        $('#myAudio').attr('src',songFileName).play(); // getting element myAudio bi its id, then setting it's src attribute and, finally, starting playback 
    });
});

and HTML for this will be following

<img src="images/play.png" class='playbtn' alt="Play Button" data-song="RWY.mp3" width="37" height="30" />
<img src="images/play.png" class='playbtn' alt="Play Button" data-song="EL.mp3" width="37" height="30" />

From now you need to add only one line to add new song button - just copy <img ... /> line, set new data-song value and... wuala!

Upvotes: 0

Related Questions