Utilize a single script to control various buttons

At work, I have a soundboard that I like to use to prank my coworkers. The soundboard has multiple buttons, each playing a different sound when clicked. Currently, I have to write a separate script for each button, which has led to 47 scripts on the page. I am looking for a better solution where I can have one script that works for all the buttons.

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

Here is an example of one of the buttons:

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

And the script for the button:

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

It occurred to me that if I could somehow define the 'sound1' on button press, I could use the same script for all the buttons. Currently, I have to define 'sound1', 'sound2', 'sound3', and so on, and create a new 'toggleSound' function for each of them.

Answer №1

One way to enhance toggleSound1 is by adding an argument:

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

When using this function, simply pass a number as an argument:

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

Answer №2

It's a bit controversial, but I have some reservations about promoting this idea...

<button onclick="toggleVolume('volume1');">I'm uncertain what all the noise is about.</button>
<button onclick="toggleVolume('volume2');">Another type of sound</button>

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

Answer №3

One effective approach involves implementing event delegation and positioning the event handler at a higher level in the code.

<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();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

In order to utilize Next.js with pkg, you must enable one of the specified parser plugins: 'flow' or 'typescript'

Utilizing next.js with the pkg in my project, following the steps outlined in this tutorial, I encountered an error when running the pkg command: > Error! This experimental syntax requires enabling one of the following parser plugin(s): 'flow, t ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

Collaborative gaming experience with three.js and socket.io

I created a basic scene in three.js that I find really fun to interact with. However, I wanted to enhance it by adding multiplayer functionality through a socket.io server. To achieve this, I prompt the user for their username: var username = prompt("what ...

Instructions for activating column resizing in MUI DataGrid

Is there a way to enable column resizing for users in MUI DataGrid? It's enabled by default on XGrid, but I would like to enable it on Datagrid as well. Any assistance is appreciated. <DataGrid className={classes.table} ...

Troubleshooting Async Issues in Node.js

I am encountering an issue with my node.js app structure, which is as follows: async.forever( function(callback) { async.series([ function(callback) { SomeFunction1(function(err, results) { if (err) callback(err); ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

When working with Nuxt 3, the referrer header may sometimes return as undefined

I am looking to capture the referrer header and store it in a cookie so that I can later use it to populate an axios request during the user's journey on my website. In my app.vue, I currently have the following code snippet: const headers = useReque ...

Utilizing AngularJS to implement a Currency Filter on the output of a personalized filter

I'm currently working on a custom filter that transforms zero values into ' - ' for display purposes. The goal is to display currency formatting for non-zero values. However, I encountered an unexpected token error while trying to implement ...

What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods? async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> { //log getAllActiveRooms return this.i.knex('users_rooms') .transacting(ctx ...

Unleashing the Array within a JavaScript Object

Currently, I am successfully receiving messages from a Server via Websocket. The received messages are in the form of a Javascript Object, and my goal is to extract the necessary data from it and update the state of my React app accordingly. Here is the c ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

Obtain the elements within a rectangular region of a webpage

Exploring how to identify a specific subset of DOM elements within a webpage that fall within the boundaries of a defined rectangle, given two points as reference. Currently developing a web gallery where each photo is enclosed within an li tag. Planning ...

value assigned to ng-model does not update beyond its scope

My issue involves binding an ng-model to an input field. Despite this, the value of the variable it is connected to does not update outside of the specific div where the directive is defined: <div input-field ng-if="startTypes.selected.value == &a ...

Understanding the concept of Angular factories in Javascript

app.service('WeatherService', function($http) { var service = {}; service.getLocation = function() { return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK"); }; service.getCurrentWeather = function(city) { var ...

Customize the appearance of a shadow-root element

Is there a way to modify the styles of a shadow element? Specifically, is it possible to extend or overwrite certain properties within a CSS class? I am currently using a Chrome extension called Beanote, which has not been updated since April 2017. There i ...

Executing the process of launching an entity and then promptly erasing it from the screen

I'm really stuck on my code and could use some help. I have a ship that is shooting and aliens moving towards it. I want the bullets to hit the aliens, remove them from the canvas, and keep doing so until all the aliens are gone. I've been thinki ...

Removing an object from the scene using three.js

Is there a way to remove an object from a three.js scene? I am trying to delete a cube when a specific key is pressed, but so far I can only clear the entire scene instead of removing just one cube. ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Is there a way for me to dynamically retrieve the input value produced by the Query?

Is there a way to retrieve the value of a dynamically created input field? $('#inputArea').append(" <input id = "arrivalTime1" type = 'number' placeholder='Arrival Time' style = 'display: none;'> " ...