Obtaining items from a function and utilizing them in a separate function

When used individually, these functions work flawlessly. However, toggling between them resulted in both arrays containing the same elements, some being multiplied based on the number of clicks.

var playerBtn1 = [];
var playerBtn2 = [];

var btn = document.getElementsByTagName("button");

playerA();

function playerA() {

for(let i = 0; i <btn.length; i++) {
btn[i].addEventListener("click", () => {
playerBtn1.push(btn[i]);
playerB();

}); 

}

return playerBtn1;
}


function playerB() {

for(let k = 0; k <btn.length; k++) {
btn[k].addEventListener("click", () => {
playerBtn2.push(btn[k]);
playerA();
});  

}

return playerBtn2;

}

Edit: I managed to resolve the issue by eliminating my functions and one Event Listener. Consolidating everything together made it work seamlessly. Below is the refined code snippet:

var playerBtn1 = [];
var playerBtn2 = [];
var click = 0;
var btn = document.getElementsByTagName("button");

for(let i = 0; i <btn.length; i++) {
btn[i].addEventListener("click", () => {
if(click % 2 == 0) {
btn[i].innerHTML = '<i class="fas fa-times fa-5x"></i>';
btn[i].disabled = "true";
playerBtn1.push(btn[i].id);
}
else {
btn[i].innerHTML = '<i class="far fa-circle fa-4x"></i>';
btn[i].disabled = "true";
playerBtn2.push(btn[i].id);
}
click++;
});

}

Answer №1

const button = document.getElementsByTagName("button");

Instead of repeatedly referencing the same HTML button every time you run this code:

playerBtn1.push(button[i])

you can clone the button element each time like this:

playerBtn1.push(button[i].cloneNode(true))

For more information, check out: https://www.w3schools.com/jsref/met_node_clonenode.asp

Answer №2

Issue resolved

const playerButtons1 = [];
const playerButtons2 = [];
let clicks = 0;
const buttons = document.getElementsByTagName("button");
    
    for(let j = 0; j < buttons.length; j++) {
        buttons[j].addEventListener("click", () => {
            if(clicks % 2 == 0) {
                buttons[j].innerHTML = '<i class="fas fa-times fa-5x"></i>';
                buttons[j].disabled = "true";
                playerButtons1.push(buttons[j].id);
            }
            else {
                buttons[j].innerHTML = '<i class="far fa-circle fa-4x"></i>';
                buttons[j].disabled = "true";
                playerButtons2.push(buttons[j].id);
            }
            clicks++; 
        }); 
        
}

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

Having issues as a Node.js novice with error messages

Here is the code I have for a basic node.js application: var http = require('http'); var fs = require('fs'); var path = require('path'); var url = require('url'); var port = process.env.port || 1337; http.createSer ...

Receiving the result as well as encountering undefined initially during AJAX request

I have a dropdown menu, and when a user selects an option, an AJAX call is made to retrieve and display data based on the selected value. If the dropdown value is 2, it triggers the AJAX request. However, I am encountering two issues: https://i.sstatic.n ...

Has the jQuery plugin object misplaced a variable?

I am in the process of developing a basic plugin using jQuery. My current approach involves creating private functions and storing variables within the jQuery object itself. (function($) { var somePrivateFn = function() { alert(this.x); } ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

How to alter the HTML view in Angular 2 after it has been processed

Here is some Angular 2 code snippet: import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: 'Waiting on port ', }) export class AppComponent { } I want to dynamically add the text "3000" ...

Error: The input for column numbers must be integer or slices, not string causing a TypeError

Recently, I started learning Python programming and encountered a TypeError while attempting to run a program. The error occurs in line 13: while okay == 1: for line in open(r'%s'%path_F,'r'): line2 = line.replace('#&ap ...

Using template literals to toggle CSS classes in React causes the button to malfunction

I'm working with a CSS module called 'styles' and this React code consists of a div containing two buttons. The state isMenuActive is used to determine if the menu is active or not. If the menu is active, the CSS class 'active' is ...

What techniques do libraries use to interpret the tick symbol syntax in JavaScript?

There are libraries that utilize the following syntax in Javascript. Is this syntax considered valid in Javascript? If not, what is the alternative method used by these libraries to handle it behind the scenes. const button = css` position: fixed; bottom ...

Wrapping elements with wrappers causes an incorrect offsetTop value to be retrieved

Previously, I used this approach for the target element and not the wrapper. However, it seems to be ineffective in this specific example. Upon running the code, some strange behaviors become apparent. The offsetTops of the sections are at 0 even before th ...

In Ruby, insert an array into another array and return the elements enclosed in square brackets

After spending some time searching, I am struggling to find a solution to push an array into another array or into a hash. I apologize if the formatting of my question is a bit messy. This is my first time posting a query on StackOverflow, so I am still le ...

What is the best way to differentiate between several elements inserted via JavaScript in my HTML code?

I'm attempting to replicate the image below using HTML and JavaScript: https://i.sstatic.net/kvmqk.jpg So far, this is what I have: https://i.sstatic.net/8iHfB.png Here's my JavaScript code: function createLink(text, parentElement) { var ...

What is the best way to connect these functions in a sequence using promises?

A new software has been developed to extract data from an online t-shirt store and then organize the product information into a CSV file. The software consists of 3 scraping functions and 1 function for writing the data. I'm currently facing challen ...

More zeroes appearing in the final result

Having an issue with my program output displaying two extra zeros upon clicking to view the content. Below is a snippet of the code in question. $(MyOrder).each(function () { var markup = '<tr data-toggle="modal" data-target="#myModal" onclick ...

Unable to transform JSON array into a string

I am encountering an issue where the server is not responding with the expected data. Instead, I am receiving a token error '<', despite trying various solutions. $(document).ready(function() { $.ajax({ url:"url", dataTyp ...

Using functions like .map in a TypeScript model may not function properly

After retrieving data from a server, I created a TypeScript model to structure the incoming data as follows: export class DataModel{ public PageNo: number public showFromDate: string public showToDate: string public gradeFieldId: number } ...

What are some recommended methods for integrating the Google Adwords Dynamic Remarketing Tag into an AngularJS framework?

I am currently working on a unique way to automatically fill in the google adwords remarketing tag. Here is the structure of the google code: <script type="text/javascript"> var google_tag_params = { dynx_itemid: 'REPLACE_WITH_VALUE', dynx ...

The query designed to conduct a thorough search using regex is experiencing some issues and not performing as expected

How can I perform an in-depth regex search in MongoDB using a JavaScript function within the query? Here's an example: db.collection.find( {$where: function() { function deepIterate(obj, value) { var new_value = new RegExp("^"+ ...

When zooming in on a d3js graph, the number of ticks begins to multiply

I added zoom functionality to a d3 line chart and it was working fine at first. However, after zooming to a certain level, the y-axis ticks started displaying decimal numbers like (3.400000001). I then included the following code: .tickFormat(d3.format(", ...

Encountering errors during the installation of packages using npm

Can someone please assist me with fixing these errors? I am a beginner in the world of web development and encountered this issue while working with react.js and setting up lite-server. Any guidance on how to resolve it would be greatly appreciated. ...

What are some effective ways to optimize a scrolling script?

Within my div element, I have a list of ordered elements (ol) that I am manipulating with drag and drop functionality using jQuery Nestable. If you could help me troubleshoot this issue, it would be greatly appreciated: How to scroll the window automatical ...