Need simplificated Function for onclick button sounds

This is my first question here sorry if I make any mistake.

I want to know how to simplificate an action(function), I have a drumkit with differents buttons with differents sounds, Im using this code: FIDDLE

JS

function play() {
var audio = document.getElementById('audio1');
if (audio.paused) {
    audio.play();
}else{
    audio.currentTime = 0
}

How can I make just one function and play different sounds in every button?

28 thoughts on “Need simplificated Function for onclick button sounds”

  1. You could try firing multiple functions from one function. Something like:

    <button onClick="play()">song1</button>
    <button onClick="play()">song2</button>
    <button onClick="play()">song3</button>
    
    function someFunc() {
        function audioOne() {
        var audio = document.getElementById('audio1');
        if (audio.paused) {
            audio.play();
        }
        else{
            audio.currentTime = 0
        };
        function audioTwo() {
        var audio = document.getElementById('audio2');
        if (audio.paused) {
            audio.play();
        }
        else{
            audio.currentTime = 0
        };
        function audioThree() {
        var audio = document.getElementById('audio3');
        if (audio.paused) {
            audio.play();
        }
        else{
            audio.currentTime = 0
        };
    }
    

    Alternatively you could also try something like:

    var audio = document.getElementById("id");
    audio.addEventListener("click", function(){alert("audio1 triggered")}, false);
    audio.addEventListener("click", function(){alert("audio2 triggered")}, false);
    
    Reply
  2. function play(id) {
    var audio = document.getElementById(id);
    if (audio.paused) {
        audio.play();
    }else{
        audio.currentTime = 0
    }
    

    call it like this:

    play('audio1');
    play('audio2');
    

    If i understand your question correctly this should work for your use-case. You basically just pass the elements id as parameter. Everytime you call the function the logic will apply to the element you specified as parameter in your function call.

    Reply

Leave a Comment