How do you trigger the playback of a specific audio file when a user clicks on it?

I'm currently working on an interactive music app that mimics the functionality of a piano. Users are able to click on different boxes on the screen, triggering a unique musical note to play.

While I initially considered manually collecting all the Ids for both the boxes and audio files, I believe there must be a simpler and more efficient approach.

An initial attempt at looping through the box elements and extracting their Ids was successful, but I encountered difficulties in retrieving the corresponding audio file names. One potential solution I thought of involved matching the box Ids with the name attribute values of the audio files, although I haven't been able to implement this yet.

Below is a snippet of the code structure:

<div id="main">
        <div id="box1" class="box"></div>
        <div id="box2" class="box"></div>
        <div id="box3" class="box"></div>
        <div id="box4" class="box"></div>
        <div id="box5" class="box"></div>
        <div id="box6" class="box"></div>
        <div id="box7" class="box"></div>
    </div>

<audio id="box1_sound" name= "notes" >
        <source src="audio/d_note.mp3" type="audio/mp3"></source>
    </audio>

Javascript Operations:

var box1 = document.getElementById('box1');
var box1Note = document.getElementById('box1_sound');

box1.addEventListener('mousedown', function() {
    box1Note.currentTime = 0;
    box1Note.play();
});

var boxName = document.getElementsByClassName('box');
var notes = document.getElementsByName('notes');

for (var j = 0; j < notes.length; j++) {
    var notesVal = notes[j].name;
    console.log(notesVal);
}

for (var i = 0; i < boxName.length; i++) {
    boxName[i].addEventListener('mousedown', function() {
        var boxId = this.id;
        console.log(boxId);

    });
}

Your assistance in solving this challenge would be greatly appreciated. Thank you!

Answer №1

If you're looking for a solution, consider this workaround:

Iterate through each box. Within each iteration, extract the ID of the box and combine it to create the audio element's ID.

For instance:

var boxes = document.querySelectorAll('.box');

for ( var i=0 ; i < boxes.length; i++) {   
    boxes[i].addEventListener('click',function(){
        sound = document.getElementById(this.id+'_sound');    
        sound.currentTime = 0;
        sound.play();
    });    
}

Check out the FIDDLE DEMO

Answer №2

How about adding an onclick event handler to each individual div? Take a look at this approach:

<span onclick="playMusic('a.mp3')" class="white">  </span>
<span onclick="playMusic('b.mp3')" class="black">  </span>
<span onclick="playMusic('c.mp3')" class="white">  </span>
<span onclick="playMusic('d.mp3')" class="black">  </span>
<span onclick="playMusic('e.mp3')" class="white">  </span>
<span onclick="playMusic('d.mp3')" class="black">  </span>

You can then implement some JavaScript that will play the specified audio file when each div is clicked. Check out this jsfiddle for a live example of how this works.

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

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Uncovering a specific element within an array using knockout techniques

I am attempting to set a variable to an element within an array that holds a particular value for a property. For instance, I want to retrieve the item with an "Id" value of 15. However, my current method only retrieves the first item in the array, regar ...

Modifications to the selected input do not impact the current state of the model

Declare 3 select inputs with hierarchical data to be chosen: <select data-ng-model="current.manufacturer" data-ng-options="c.name for c in manufactures"></select> <select data-ng-model="current.mark" data-ng-options="c.name for c in current ...

Tips for optimizing Slider Code to showcase an expanded selection of slides

I am currently troubleshooting a slider code on my ASP.NET website. After examining the HTML, JS, and CSS from the page theme, I noticed that only two slides are being displayed. However, when attempting to add a new slider HTML and adjusting the CSS for t ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Utilizing a foreach loop to control the behavior of two distinct radio buttons as a unified

Can someone help me with a code containing a 5 star rating system (radio button) for two different questions? The issue is that the ratings for each question are linked, so when I make a selection in one question, it clears the selection in the other. It& ...

Tips for obtaining validation errors on input elements in React when the input field is of type "file"

Currently, I am utilizing Material UI to cover the input component with icons. However, I have encountered an issue where there is an input element hidden and as a result, validation errors are not being displayed. The library I am using for validation i ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

The elements at the bottom of the Google homepage do not stay in place when hovering

I'm facing an issue and seeking guidance on how to make the footer and 'Google in different languages' fixed when hovering over the buttons. I'm attempting to create this on my own without referencing the Google homepage code in Chrome ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

Is it possible to implement smooth scrolling in HTML without using anchor animation?

Is it feasible to implement a more seamless scrolling experience for a website? I'm referring to the smooth scrolling effect seen in MS Word 2013, but I haven't come across any other instances of this. I've heard that AJAX can make such th ...

Improved method for transferring multiple form input values from a child to a parent window

I am working on a project where I have a child window containing multiple radio buttons. My goal is to send all the selected values from these radio buttons to the parent window. Currently, I am achieving this by creating a JavaScript string that contains ...

Disappear element after a brief moment

What is the best way to temporarily hide an element and then have it reappear after a second? var targetElement = document.getElementById("myElement"); targetElement.onclick = function() { this.style.display = "none"; setTimeout(function(){ ...

I'm curious if it's possible to utilize Raspberry Pi GPIO pins within a JavaScript frontend

Is it possible to utilize Raspberry Pi's GPIO pins in Javascript? Specifically, I am interested in reading the values of the Raspberry Pi PIR sensor without having separate Python and Javascript applications. Ideally, I would like a solution that inte ...

CSS behaving strangely with the height property

I've run into a specific issue with a div element that contains multiple buttons. I am trying to adjust the height and position of one button so that it takes up space above the other buttons, but every time I make changes to its height and position, ...

In Laravel, the text-overflow:ellipsis property fails to function properly when trying to display unescaped data

Encountering an issue with the property text-overflow:ellipsis. The ellipsis at the end of the truncated text is not showing up as expected. To maintain formatting without escaping data in ckeditor, I am using: {!! $treatment->description !!} speci ...

What is the best approach for managing validations on a field-by-field basis within a Formik FieldArray?

Scenario: When there are 3 participants, each participant will receive a set of questions. However, the display of each question is dependent on a list of "applied tickets" associated with the question. TLDR; I need to understand: if it's possible ...

Creating a unique 3D model through specified coordinates with the use of THREE.js

I possess an array consisting of (x,y,z) vertices coordinates as well as a facets array that stores the indexes of vertices (taken from the first array) for each facet. Each facet may have a varying number of vertices. Is there a way to construct a unique ...