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

jquery-validation error in gulp automations

I've encountered a sudden error in my gulp build related to jQuery validation. There haven't been any recent changes that would trigger this issue. Interestingly, one of my colleagues is experiencing the same problem, while another one is not. We ...

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Revolutionary CSS and jQuery for an Exceptional Top Navigation Experience

I would like to create a top navigation similar to the one on Facebook, using CSS and jQuery. Here is an example: Additionally: Notice how the arrow in the popbox always remains beneath the selected navigation item, and all popboxes have the same width. ...

Laravel error message for unresolved symbolic link

Previously, I had developed a form for uploading profile pictures using the code snippet below, $image = $request->file('avatar'); $pass = Hash::make($request->password); if($image!=null){ $avatar_na ...

Using jQuery's toggleClass method to implement CSS transformations

I have a question about this situation Each time the button is clicked, jQuery toggles the class: .transition { background-color: #CBA; transform: translateX(100px) scale(0.5) rotate(180deg); } Within the <div class="container2"> And upon ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...

The additional cost associated with using a React hook is called the "

Our system includes a theme context provider that passes down a theme to all child components, calculated based on the device's dimensions. We can easily access these values using the useTheme hook in any component. In addition, we have a constants f ...

How can you set the listbox in Sumo Select to always be open?

Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

The compatibility between Babel 7 and the preset-es2015 is not very reliable

After reading this useful tutorial on implementing server-side rendering with create-react-app, I attempted to execute the following code snippet: require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], ...

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

The boundary of embedded components

I am looking for CSS code that will allow me to arrange all elements with specific indents, such as placing the first element on the left side of the page, followed by an image with some indentation, and so on. <div class="container-fluid"> &l ...

Is there a way to adjust the position of ::before elements without affecting the border placement?

I'm struggling with an element that has a CSS style ::before to display an arrow-up inside a black circle. Check out the code here The issue I'm facing is that the character \25b2 isn't centered vertically within the circle. Adjustin ...

Center and justify image inside flexbox using MUI

Can someone explain why my image appears centered but not justified? I'm feeling confused about this. <Box sx={{ display: 'flex', minHeight: '100vh', alignItems: 'center', flexGrow ...