What is the best way to trigger various sound files with a click?

I recently created a basic matching game that includes audio files for different cards. The code snippet below shows how I incorporated these audio files:

cardList.map((cardItem) => {
var card = document.createElement("li");
card.classList.add("card");

var img = document.createElement("img");
img.src = [cardItem.img]


  card.appendChild(img);

//audio starting here

audio = new Audio(cardItem.sound);
card.appendChild(audio);

audio.id += ' ' + cardItem.card;

deck.append(card);

card.className += ' ' + cardItem.name;
});
}

In my startGame() function, I made sure to include an eventListener that triggers audio.play() when a card is clicked.

While inspecting the dev tools, I noticed that each card has its corresponding audio element. However, upon clicking on the cards, only one audio file plays regardless of the specific card selected.

You can view the code on my GitHub repository: https://github.com/cMikolai/guitar-colour-system-game/blob/master/js/app.js

Could anyone provide guidance on how I can successfully play the sound associated with the card being clicked?

Answer №1

After downloading and experimenting with your code, I discovered that the function responsible for playing audio is located within the startGame() function in your app.js file.

app.js:

audio = []; // initializing a local variable

...
... 

// additional code

function startGame() {

  // more code

  for (var i = 0; i < clickedCard.length; i++) {
    clickedCard[i].addEventListener("click", function( event ) {
    this.classList.add("open", "show");

    openCards.push(this.getAttribute("class"));

    audio.load();
    audio.play(); // this line triggers the audio playback

    matchCards();
    starRating();

    }, false);
  }
}

It seems that the audio being played is coming from the local variable audio, rather than from the selected card.

In order to resolve this issue, you'll need to correctly identify the selected card and play its corresponding audio instead of relying on the local variable for audio playback.

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

Utilize a directive to showcase information stored within the scope

Struggling to grasp the concept of directives and encountering a bug along the way. To see my example in action, check out the codepen I've created here In my scope called "movies," I have 3 movie titles that I want to display using a directive. va ...

Jquery plugin fails to function following ajax onchange event

Below is the JQuery code: <script src="./minified/jquery.sceditor.bbcode.min.js"></script> <script> var loadCSS = function(url, callback){ var link = document.createElement('link'); ...

Logic in ReactJS for displaying the application

Struggling a bit with React here. Currently working on an application that fetches user data from an external endpoint and saves it in local storage. I've noticed that my react-app is rendering the html before the state for that data is updated, resul ...

Emphasize SELENIDE rows

My goal is to achieve the following: @Test public void tableTest() { getDriver().get(BASE_URL + "tabulka.php"); List<WebElement> rows = getDriver().findElements(By.xpath("//table//tbody//tr")); for (We ...

Tips for customizing the appearance of Bootstrap 5.0 popovers on the fly

Back in Bootstrap 4.0, you could easily change the popover content dynamically based on the selector or reposition it using the $tip property. $("body").popover({ container: 'body', content: 'loading...', html: tru ...

Customizing background images based on views in AngularJS

I am new to working with angularJS and I am attempting to set different backgrounds for various pages. Unfortunately, I am running into some challenges because my view is connected to elements in my index.html. index.html <div class="top-container"> ...

Shifting content results in Vue transitions

I've encountered an issue with transitioning content shifts. My data array is displayed in different areas of the DOM based on the state. The main idea: OPEN feedback 1 [ complete ] feedback 2 [ complete ] feedback 3 [ complete ] CLOSED Goal: ...

After a successful login, Angular will once again redirect the user to the login page

I successfully implemented the back-end using nest-js to handle authentication with mongo-db. Registration and login are working fine, but I face an issue after logging in with a successful result - when I refresh the page, it redirects me back to the logi ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

What makes the creation of Javascript objects so flexible and dynamic?

Recently, I've been exploring the concept of creating new objects in JavaScript. It's interesting to note that in JS, every object creation is dynamic. This allows you to create an object and then add properties later on. Even fields created in t ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Utilizing LocalStorage in conjunction with the redux state management

Currently, I am working on a single-page application using React and Redux. I have encountered the need to store certain data locally and ensure that it remains synchronized with the appState in local storage, even after a page refresh. Despite being new ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

What is the best way to send a user-provided input to my cloud function?

Currently, I am delving into the realm of Cloud Functions for Firebase and have successfully implemented an auth trigger by following a tutorial. However, I am now facing a challenge in passing the username that the user desires to use to my auth event. ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

"Interactive" - Utilizing javascript and html5 to create engaging game animations

Imagine I have a base class that looks like this: function Tile(obj) { //lots of default variables such as colors and opacity here } Tile.prototype.Draw = function () { ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," ...

Here's a method to extract dates from today to the next 15 days and exclude weekends -Saturday and Sunday

Is there a way to generate an array of dates starting from today and spanning the next 15 days, excluding Saturdays and Sundays? For example, if today is 4/5/22, the desired array would look like ['4/5/22', '5/5/22', '6/5/22' ...

What is the process for generating a printable report using HTML, CSS, and ASP.NET Core?

I am looking to create a customizable report using HTML and CSS, however I am not familiar with designing forms like pay slips that can be easily printed. Please see the images I have shared below for reference. Any help or guidance would be greatly apprec ...

Having difficulty encapsulating three.js rendered particles within a single div

I'm facing an issue where the particles generated by my three.js project are not contained within a specific div or html element as intended. Instead of staying within the designated boundaries, the particles are spreading across the entire DOM witho ...