Question

I cant figure out why it is not working. Since its nothing too special I searched on the web - and here but all I found was either tutorials without the variable or questions with too specific questions.

Can anyone guide me on this?

<html>
<head>
<title>Test</title>
<script type="text/javascript">

function changeaudio(x);
{

  document.getElementById("audioplayer").src=x+".mp3";
  document.getElementById("image").src=x+".png";
}

</script>
</head>
<body>
<center>
<img id="image" src="1.png">
<audio id="audioplayer" src="1.mp3" controls autoplay loop>
Your browser does not support the audio element.
</audio> 
<br>

<input type="button" id="play" value="Play 1" onclick='changeaudio(1)"' />
<input type="button" id="play2" value="Play 2" onclick='changeaudio(2)"' />
<input type="button" id="play3" value="Play 3" onclick='changeaudio(3)"' />
</center>

</body>
</html>
Was it helpful?

Solution

Remove the ; after your function definition: function changeaudio(x); should become:function changeaudio(x)

Also, your onclick syntax is wrong: onclick='changeaudio(1)"' should be: onclick="changeaudio(1)".

Your final code should look like this:

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
        function changeaudio(x)
        {
            document.getElementById("audioplayer").src=x+".mp3";
            document.getElementById("image").src=x+".png";
        }
        </script>
    </head>
    <body>
        <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
                Your browser does not support the audio element.
            </audio> 
            <br />
            <input type="button" id="play" value="Play 1" onclick="changeaudio(1)" />
            <input type="button" id="play2" value="Play 2" onclick="changeaudio(2)" />
            <input type="button" id="play3" value="Play 3" onclick="changeaudio(3)" />
        </center>
    </body>
</html>

jsFiddle Demo

OTHER TIPS

for a jquery approach :

$(function(){
    $('.play').each(function() {
       var mp3 = $(this).attr("id"); 
        $(this).click(function(){
           $('#audioplayer').attr("src", mp3+".mp3"); 
           $('#image').attr("src", mp3+".png"); 
        });
    });

});

 <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
            </audio> 
            <br />
            <input type="button" class="play" id="1" value="Play 1" />
            <input type="button" class="play" id="2" value="Play 2"  />
            <input type="button" class="play" id="3" value="Play 3" />
        </center>

jsFIDDLE DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top