Incorporating HTML5 audio elements in JavaScript

I am working on a project where I need to create a grid of 16 audio files with separate links for each in HTML, CSS and JavaScript. Each box in the grid should link to a different audio file.

My initial thought was to use a table to achieve this, so I created one using HTML/CSS. Here is an example of one of the cells (TD) that I used:

<td id="A" class="squareA" type="button";><audio src="music/work_it.wav">Work It</td>

After setting up the HTML structure, I attempted to add event listeners and get elements by tag name using JavaScript but ran into some issues. If anyone has any suggestions or tips, I would greatly appreciate it!


document.addEventListener("DOMContentLoaded", function(event)) {
var audio = document.getElementsByTagName('audio')[0];
  
  workit.addEventListener('click' function());

Answer №1

If you're trying to target the `audio` tag within each `td`, but are lacking a unique identifier, there's a simple solution. By making a small addition to your code, you can easily address this issue.

<td id="A" class="squareA" type="button";>
   <audio id="audio-A">
     <source src="music/work_it.wav" type="audio/wav">
   </audio>
   Work It
</td>

By using specific `id`s, you can now locate each tag effortlessly.

Alternatively, if you include `controls` in the `audio` tag, users will be able to activate the default browser player and play the file without any additional coding.

<audio controls>
   <source ... etc
</audio>

However, if `controls` are absent (or set to `controls="false"`), the default browser player won't appear. If your goal is to play the audio file with a click event, this may be the desired outcome.

At this point, the `id`s of Audio tags might not be useful because without `controls`, nothing will be displayed for users to interact with. In such cases, you would need to target all of their respective `td` elements in the table.

If you haven't already done so, consider adding an `id` attribute to the audio table (e.g., 'audio-table'), allowing you to use `.addEventListener()` on each `td` box with a function called upon page loading:

function addEvents2Table() {
  /* assuming the table has an
     id of 'audio-table' here */
  var audioTable = document.getElementById('audio-table');

  /* collect td tags */
  var tdTags = audioTable.getElementsByTagName('td');
  var len = tdTags.length;

  /* add a 'playAudio' function call
     to each td when clicked */
  while(len--) {
    tdTags[len].addEventListener(
      'click', playAudio, false
    );
  }
}

/* trigger 'addEvents2Table()' on page load */
window.onload = function() {
  addEvents2Table();
};

Now, when a `td` in the table is clicked, the `playAudio()` function will execute. All that remains is to define this function based on your HTML structure:

In the first code snippet provided above, an `id` was added to the audio tag within a td-tag with an `id` of "A." This initial setup will prove valuable now:

function playAudio(event) {
  /* fetch the 'id' of the clicked element */
  var tagID = event.target.id;

  /* append it to 'audio-' */
  var audioID = 'audio-' + tagID;

  /* locate the corresponding audio tag */
  var audioTAG = document.getElementById(audioID);

  /* initiate playback */
  audioTAG.play();
}

There are various considerations to bear in mind moving forward. Are you comfortable with simultaneous audio playback in the browser? Would you like users to stop an audio clip? As currently implemented, clicking multiple boxes rapidly could result in overlapping audio playback attempts. Additionally, clicking a box while its corresponding audio is playing may create issues.

Nevertheless, these suggestions should provide a solid starting point. Feel free to leave a comment if further explanation is needed.

For reference, here is MDN's audio tag page.

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

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

An error was encountered: SyntaxError - An unexpected token '!' was found

I am having trouble creating a react cluster map. I encountered a SyntaxError, and I'm not sure what went wrong. Initially, my map was working fine, but after using the use-supercluster npm package, it started showing an Uncaught SyntaxError: Unexpect ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

What is the best way to adjust the fontSize of text within a table using Material UI?

In my Material UI table, I am attempting to adjust the fontSize of the contents. However, when I try to modify it using the style={{}} component, the changes are not being applied. <Grid><Typography variant="body1">Fiscal Year </Typography&g ...

Unpredictable Dependency Outcomes in Node.js

Encountering a warning while running yarn install where all dependencies are installed, but a specific warning is triggered: Warning: Pattern ["esprima-fb@~3001.0001.0000-dev-harmony-fb"] is attempting to unpack in the same destination "/Users/Me/Librar ...

Curious about how to swap the positions of these two divs?

After wrapping them in divs and adding inline-block to both elements to display them side by side, I'm now exploring options to switch their positions. Specifically, I'd like the right element to be on the left. Any ideas on how to achieve this? ...

Stop the page from scrolling when a modal is displayed in React

I've encountered an issue with my custom modal component where the background stops scrolling when the modal is open. Initially, I attempted to solve this by using the following code: componentDidMount() { document.body.style.overflow = 'hi ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...

Automatically populating fields in Laravel 8 after selecting a value from a dropdown menu

Having an issue once again.. If I choose the Banjarmasin-Jakarta route, the shipping cost field will be filled with 1.750.000 However, if I want to select "search shipping route" again, the shipping cost field will be filled with 0 Select "search shippi ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

Guide to Displaying Items in Order, Concealing Them, and Looping in jQuery

I am trying to create a unique animation where three lines of text appear in succession, then hide, and then reappear in succession. I have successfully split the lines into span tags to make them appear one after the other. However, I am struggling to fin ...

Tallying the number of messages on Facebook

Greetings everyone! I have been utilizing the Facebook JS SDK to retrieve the number of messages sent. Below is the code snippet: <script> function statusChangeCallback(response) { console.log('statusChangeCallback'); console.log ...

Show the URL hash as url.com/something#/ rather than url.com/something/#/

I'm encountering a peculiar issue with my Angular v1.6.5 setup. My routes seem to be acting strangely, for example: $routeProvider .when('/', { templateUrl: 'myTemplate', controller: 'myController', method: &apo ...

Encountering a problem with parsing a JSON object using the .map

After receiving this JSON response, my main goal is to extract the value located in the identifier. By utilizing console.log, I am able to analyze the structure of the object: Object {rows: Array[33], time: 0.015, fields: Object, total_rows: 33} fields: O ...

Tips for combining two htmlelements together

I have two HTML table classes that I refer to as htmlelement and I would like to combine them. This is similar to the following code snippet: var first = document.getElementsByClassName("firstclass") as HTMLCollectionOf<HTMLElement>; var se ...

Browsing through dual snap points simultaneously on Google Chrome

I'm currently developing a website that incorporates scroll snapping for 3 viewport-sized <section> elements set up like so: html, body { scroll-behavior: smooth; scroll-snap-type: mandatory; scroll-snap-points-y: repeat(100vh); scrol ...

Efficiently submitting multiple forms in a single click

On my photo portfolio admin page, I have created a feature to caption, keyword, and credit each photo. Previously, I had multiple forms listed dynamically with submit buttons for each form. With over 20 photos/forms on the page, this process became tedious ...

Automatically appending textarea value in HTML tag upon form submission via JQuery

When a form is submitted through JQuery, the HTML tag automatically adds textarea value. This is my JQuery code: $('#calling').click(function() { $('#myform').submit(); }); Within my form, there is a textarea element: <textar ...

Troubleshooting Issue with Query Functionality in MEAN App's Find Request

I'm facing some challenges while working with queries in my MEAN App. Specifically, I am attempting to retrieve data that matches the input entered into a search field: $scope.searchInput = function(search){ $http({ method: 'GET', url: ...

Troubleshooting problems with Bootstrap datepicker in a Vue project

I am facing a problem with the b-datepicker feature while trying to select a date. The dates are not appearing correctly, as shown in the image linked below. Here is my code: <b-form-group class="my-3" > <b-input-group> ...