qtt qtt
qtt qtt

Reputation: 187

How to shorten repeated functions

How can I make this code more efficient or shorter. I feel like there are too much repeated functions. Is there a way to make this all in one and shorter?

<html>
<body>

<button onclick="myFunction()">Audio 1</button>
<button onclick="myFunction2()">Audio 2</button>
<button onclick="myFunction3()">Audio 3</button>


<script>
function myFunction() {
    var a = new Audio('Link1');
    a.play();
}

function myFunction2() {
    var b = new Audio('Link2');
    b.play();
}

function myFunction3() {
    var c = new Audio('Link3');
    c.play();
}

</script>

</body>

Upvotes: 1

Views: 113

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could add a parameter to the function for the link.

HTML:

<button onclick="playAudio('link1')">Audio 1</button>
<button onclick="playAudio('link2')">Audio 2</button>
<button onclick="playAudio('link3')">Audio 3</button>

Javascript:

function playAudio(link) {
    var audio = new Audio(link);
    audio.play();
}

Upvotes: 4

dhilt
dhilt

Reputation: 20744

Using function call parameter, try following:

<button onclick="doPlay(1)">Audio 1</button>
<button onclick="doPlay(2)">Audio 2</button>
<button onclick="doPlay(3)">Audio 3</button>


function doPlay(index) {
    var a = new Audio('Link' + index);
    a.play();
}

Upvotes: 2

Related Questions