To avoid duplication of code, you need to introduce a function for the common behavior, with parameters for the variable parts.
Starting from the first part of your example:
$(document).ready(function(){
$("#play-bt1").click(function(){
$("#audio-player1")[0].play();
$("#message").text("Music started");
})
$("#pause-bt1").click(function(){
$("#audio-player1")[0].pause();
$("#message").text("Music paused");
})
$("#stop-bt1").click(function(){
$("#audio-player1")[0].pause();
$("#audio-player1")[0].currentTime = 0;
$("#message").text("Music Stopped");
})
})
We can wrap this building block in a function. The first step is to find a good name for this function. Since the function initializes a player when the document is ready, an explicit name is initPlayerWhenDocumentReady
. Wrapped in the function, the code becomes:
function initPlayerWhenDocumentReady(){
$(document).ready(function(){
$("#play-bt1").click(function(){
$("#audio-player1")[0].play();
$("#message").text("Music started");
})
$("#pause-bt1").click(function(){
$("#audio-player1")[0].pause();
$("#message").text("Music paused");
})
$("#stop-bt1").click(function(){
$("#audio-player1")[0].pause();
$("#audio-player1")[0].currentTime = 0;
$("#message").text("Music Stopped");
})
})
}
The next step is to extract parameters for the variables parts. One possibility would be to add separate parameters playerId
, playButtonId
, pauseButtonId
, stopButtonId
.
But on second look, it appears that all the identifiers follow the same format, and only the number at the end changes: 1
, 2
, 3
. Thus, we can just add a single parameter for the number, playerNumber
:
function initPlayerWhenDocumentReady( playerNumber ){
$(document).ready(function(){
$("#play-bt"+playerNumber).click(function(){
$("#audio-player"+playerNumber)[0].play();
$("#message").text("Music started");
})
$("#pause-bt"+playerNumber).click(function(){
$("#audio-player"+playerNumber)[0].pause();
$("#message").text("Music paused");
})
$("#stop-bt"+playerNumber).click(function(){
$("#audio-player"+playerNumber)[0].pause();
$("#audio-player"+playerNumber)[0].currentTime = 0;
$("#message").text("Music Stopped");
})
})
}
You can then call this function to initialize the three players:
initPlayerWhenDocumentReady( 1 );
initPlayerWhenDocumentReady( 2 );
initPlayerWhenDocumentReady( 3 );
The calls to the same function with different values allow to run similar code while reducing duplicate code: only the call is repeated.
And even this limited duplication can be avoided, by using a loop, here defined in a new function, initPlayers
, which takes the total number of players as parameter:
function initPlayers( total ) {
for (var i = 1; i <= total; i++ ) {
initPlayerWhenDocumentReady( i );
}
}
initPlayers( 3 );