The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after the initial click. Unfortunately, I can't use jQuery because it doesn't work in Chrome. Here is my code:

if(x<=1200&&x>=600){
    var n=true;
};
if(x<=1200&&x>=600&&n==true){
    document.getElementById('a').onclick = function(){
        audio.play();
        n=false;    
    }
}
else{
    n=false;
}

Answer ā„–1

The functionality of your code is to attach a click event listener to an element, and thereafter the click handler will execute regardless of the x value since there are no conditional checks within the click handler.

A better approach would be to set up the click listener only once and incorporate a check for the value of x within it. Here's an example:

document.getElementById('a').onclick = function(){
  if(x <= 1200 && x >= 600 && n == true) {
    audio.play();
    n = false;    
  }
}

Here's a demonstration (I've substituted audio playback with div highlighting, but the concept remains unchanged):

var r = document.getElementById('r');
var n = true;
var x = 1000;
document.getElementById('a').onclick = function(){
  if(x <= 1200 && x >= 600 && n == true) {
    r.className = 'playing';
    n = false;
    printN();
    setTimeout(function(){
      r.className = '';
    }, 2000);
  }
}

function toggleN(){n = !n;printN()}
function printN(){document.getElementById('n').textContent = 'n is set to ' + n;}
function randomizeX(){x = Math.floor(Math.random() * 1200);printX()}
function printX(){document.getElementById('x').textContent = 'x equals ' + x;}
#r {display: inline-block; width: 50px; height: 50px; background: #ccc; transition: background 1s linear;}
#r.playing {background: green}
<button id="a">Hit me</button><br><br>
<div id="r"></div>
<p id="x">x equals 1000</p>
<p id="n">n is set to true</p>
<button onclick="toggleN()">Toggle n</button>
<button onclick="randomizeX()">Randomize x</button>

Answer ā„–2

It seems like you may be attempting to achieve a specific task, so here is a suggestion:

if(y<=1200&&y>=600){
    var m=true;
    var pressed = false;
    };
    if(y<=1200&&y>=600&&m==true || pressed==true){
    document.getElementById('b').onclick = function(){
    audio.play();
    m=false;
    pressed = true;
        }
    }
    else{
        m=false;
        pressed = false;
   }

Answer ā„–3

It seems like this code will meet your requirements, based on my understanding of your request.

There is no need to repeatedly check x and n, as n only becomes true when x falls within the specified ranges.

var ab = document.getElementById('a');
var n = false;

if (x <= 1200 && x >= 600) {
  n = true; // Setting n to true when x is within range.
} else {
  n = false; // Resetting n if x goes out of range.
}

ab.onclick = function() {
  if (n) {
    audio.play();
  }
}

Please be aware that if a user clicks the button multiple times, the audio will play accordingly each time. To prevent this from happening, you may consider introducing another variable to track if the user has already clicked once. The solution for controlling repeated clicks depends on your specific setup and whether users should be able to trigger the audio multiple times in succession. Feel free to reach out with more details for a tailored solution.

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

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

Should you include the dollar sign in a Vue HTML variable or not?

Iā€™m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Guide to sending a specialized SPL token using the libraries '@solana/web3.js' and '@solana/sol-wallet-adapter'

Attempting to transfer a custom SPL token using the solana-wallet adapter is proving to be challenging due to difficulty in obtaining the wallet's secret key for signing the transaction. Although I have reviewed resources on writing the transfer code ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

Creating a JavaScript function for a custom timed traffic light sequence

Currently, I am facing a challenge with my high school project of creating a timed traffic light sequence using JavaScript for my upcoming exams. Unfortunately, I feel quite lost and unsure about how to proceed. My initial plan involves formatting the valu ...

Refining information and displaying it alongside the "indelible" data - react

I recently implemented a TextField component from the MUI library, along with a useRef hook to capture user input "live" as they type. The goal is to filter rates based on the characters entered by the user. Currently, I am working with an array of rate ke ...

Failed to retrieve information using a custom header in the HTTP request

My AngularJS code works well without the header option. $http.get(env.apiURL()+'/banks', { headers: { 'Authorization': 'Bearer '+localStorageService.get('access_token') } }) Here is the request: OP ...

The error message "TypeError: usert.addItem is not a function" indicates that

Currently in the process of developing a discord bot using discord.js, sequelize, and sqlite for database management. Encountering an issue with a custom function that is not being recognized as defined by the terminal, despite me confirming its definition ...

Why isn't this ajax script able to successfully transmit the data?

I'm having some trouble sending a JavaScript variable to a PHP file in order to create a query. Here's the script I've been using, but unfortunately it doesn't seem to be working. Any assistance would be greatly appreciated. <select ...

Using Knockoutjs to fetch and display server-side data within the MVC framework

My goal is to initialize my knockoutjs viewmodel with data from the server. In my ASP.Net MVC project, I achieve this by passing a mvc viewmodel to the view: public ActionResult Edit(int cvId) { CV cv = repository.FindCV(cvId); //auto mapper mapp ...

Retrieving data in [slug].js using Reactjs

I am currently working on a project in Reactjs utilizing the "nextjs" framework. I have successfully managed to retrieve data (specific blog details) based on the slug([slug.js]). However, I now need to display data from all other blogs within the same c ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

An advanced view engine capable of handling both ajax requests and direct function calls

In Node.js (Express), I am seeking a method to present a template in two different ways: one normally as HTML and the other as JSON, specifically for Ajax requests. Assume I have a swig template structured like this: {% extends 'layout.html' %} ...

Top method for passing props from child to parent React component

I am facing a challenge with passing data from child to parent components in React. I have an array that I need to save in my database, and I have set up a Parent component (AuthenticationPage.js) and a Child component (SignupForm.js) for this purpose. The ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

How to style text in CSS with a numbered underline beneath

Is there a way to apply underlining to text and include a small number underneath the underline in a similar style shown in this image, by utilizing css, html, or javascript? ...

Tips for generating dynamic JSON: Organize the data by filtering it and creating key-value pairs for the appropriate JSON objects

How can I generate dynamic JSON based on input, filter data, and create appropriate key-value pairs for JSON objects? The database schema can be viewed https://i.sstatic.net/iP1JS.png Although I attempted the following code, it did not produce the desi ...