Grizzle
Grizzle

Reputation: 1

One Script for multiple buttons

I've got a soundboard I use at work to annoy coworkers. It has multiple buttons, that play or stop a sound. Right now each button has its own script to play the sound. So I'm up to 47 sounds on the page and have to write this script for each one. I'd like to clean that up and have a one smarter script that works for all of them. my buttons look like:

<button onclick="javascript:toggleSound1();">I don't know what we're yelling about.</button>

Then I have the definition of the audio element:

<audio id="sound1" src="sounds/dontknowwhatwereyellingabout.wav"></audio>

and the script:

<script type="text/javascript">
function toggleSound1() {
  var audioElem = document.getElementById('sound1');
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.pause(); audioElem.currentTime = 0;
}
</script>

So it seems to me that if i could define the 'sound1' on the press in each button the same script should work for each button. as I have it now I have to define 'sound1' 'sound2' 'sound3' and so on, and point a new 'togglesound' at each of them.

Upvotes: 0

Views: 629

Answers (3)

Joe Hanink
Joe Hanink

Reputation: 4847

a better way is to use event delegation, and put the event handler higher up

<div onclick="handleAudio(e)">
  <button data-audio="1">I don't know what we're yelling about.</button>
  <button data-audio="2">Some other sound</button>
</div>

function handleAudio(e) {
  var audio = document.getElementById('sound' + e.target.dataset.audio);
  audio.play();
}

Upvotes: 0

mdickin
mdickin

Reputation: 2385

I'm not sure how I feel about encouraging this, but...

<button onclick="toggleSound('sound1');">I don't know what we're yelling about.</button>
<button onclick="toggleSound('sound2');">Some other sound</button>

<script type="text/javascript">
function toggleSound1(soundId) {
  var audioElem = document.getElementById(soundId);
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.pause(); audioElem.currentTime = 0;
}
</script>

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

You could rewrite toggleSound1 to take an argument:

function toggleSound(num) {
  var audioElem = document.getElementById('sound' + num); // append the number to "sound" (sound1, sound2, etc.)
  if (audioElem.paused) {
    audioElem.play();
  } else {
    audioElem.pause();
  }
  audioElem.currentTime = 0;
}

Then to use it, you could just pass the number to the function:

<button onclick="javascript:toggleSound(1);">I don't know what we're yelling about.</button>

Upvotes: 1

Related Questions