The JavaScript audio is not working for the first three clicks, but starts playing smoothly from the fourth click onwards. What could be causing this issue?

$(".btn").click(function(event){
                    playSound(event.target.id);
              });

              function playSound(name){
                $("." + name).click(function() {
                  new Audio("sounds/" + name + ".mp3").play();
                });
              }

The function is being called, but the audio doesn't play for the first 3 or 4 clicks. From the 4th or 5th click onwards, it functions correctly. This issue occurs in both Brave and Chrome browsers. What could be causing this problem?

Answer №1

The issue you're facing is that you are setting up the audio play function on the same button click instead of actually playing it.

  1. $(".btn").click - This line sets up the onClick event for every element with the class .btn.
  2. You are passing the id of the clicked button to the playSound function.
  3. Things get confusing here: $("." + name).click - This line sets up another click event for the class name, which is actually the id of the clicked button, and this doesn't make sense.

I assume your intention was to play the audio when the button is clicked.

Here's the correct code to achieve it:

$(".btn").click(function(event) {
  playSound(event.target.id);
});

function playSound(name) {
  new Audio("sounds/" + name + ".mp3").play();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="btn" id="name1">click to play</button>
<button class="btn" id="name2">click to play</button>
<button class="btn" id="name3">click to play</button>

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

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

Is there a way to make the header reach the full width of the page?

Is there a way to make my header extend across the entire page? I attempted using margin-left and right, but it didn't yield the desired outcome. Header.css .header{ background: green; height: 70px; width: 100%; display: flex; ju ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

Effortlessly saving money with just one click

I have a search text box where the search result is displayed in a graph and then saved in a database. However, I am facing an issue where the data is being saved multiple times - first time saves properly, second time saves twice, third time three times, ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

I'm looking for guidance on how to properly implement onChange in this particular script. Any help with the correct syntax

Can someone help me with the correct syntax for writing onChange in this script? I want to integrate these phpcode into my script. Here is the Javascript code: ih+='<div class="form-group drop_bottom" id="select_one_'+extra_num+'">< ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

Extract data from JSON object on the server side

Within my web service, I have a method that returns a JSON object: {name:'xx'} When making an Ajax request and parsing the response with 'eval', I encountered an issue. onComplete:function(req){ var data=eval(req.responseText); / ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

Resolving the issue of nested modals within Bootstrap

I am experiencing some issues with my customer visits list page. When I try to add a visit, it opens a bootstrap popup ("#Pop1") to record the visit details. Within this modal, there is an option to add a new customer on the spot, which then triggers anoth ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

The functionality of WrapAll is not functioning properly in React JS

$('p').wrapAll($('<div class="wrapper"></div>')); .wrapper { background: #EEE; margin: 10px; padding: 5px; border: 1px solid black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery. ...

Utilizing JavaScript variable modifiers for enhanced functionality

I'm trying to find a way to perform a case-insensitive search for a variable within a string. To achieve this, I'm using the /gi modifier to ignore case sensitivity. However, the challenge arises because identifiers only accept direct strings rat ...

Secure verification is a critical element within the core component of React JS

Creating a user-based application using Meteor (v1.3) requires strong authentication and authorization mechanisms. I found an insightful example by the author of Flow Router that delves into setting up authentication and authorization using Flow Router. h ...

What is the best approach to retrieve a JSON object from a form exception that has a specific name?

I have a certain form with input fields. My goal is to generate a JSON object from the form, excluding any input whose name is "point". However, my code doesn't seem to be working properly when I use the "not()" function. What am I doing wrong and how ...