implementing a button's decrease and increase functionality in JavaScript

Whenever the button is clicked, it changes its color to red. Additionally, a counter increments with each click. However, I want the counter to be dynamic so that when the button is unclicked, the counter decreases as well. Unfortunately, I am facing difficulty achieving this and no errors are being displayed.

var buttons = document.getElementsByClassName("button");
var count = 0;
var disp = document.getElementById("display");
for (let i = 0, l = buttons.length; i < l; i++) {
  buttons[i].addEventListener('click', function() {
    buttons[i].classList.toggle('active');
    if (this.classList.contains("active")) {
      if (!this.classList.contains("active")) {
        count--;
        disp.innerHTML = count;
      }
      count++;
      disp.innerHTML = count;
    }

  })
}
.active {
  background-color: #E68352 !important;
}

.button {
  background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A" />
<input type="button" id="button2" class="button" value="B" />
<input type="button" id="button3" class="button" value="C" />

<p>
  Button Clicked <span id="display">0</span> Times
</p>

Answer ā„–1

It is necessary to incorporate the use of else, as your second if statement will never be executed in its current form:

var buttons = document.getElementsByClassName("button");
var count = 0;
var disp = document.getElementById("display");
for (let i = 0, l = buttons.length; i < l; i++) {
  buttons[i].addEventListener('click', function() {
    buttons[i].classList.toggle('active');
    if (this.classList.contains("active")) {
      count++;
    } else {
      count--;
    }
    disp.innerHTML = count;
  })
}
.active {
  background-color: #E68352 !important;
}

.button {
  background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A">
<input type="button" id="button2" class="button" value="B">
<input type="button" id="button3" class="button" value="C">

<p>
  Button Clicked <span id="display">0</span> Times
</p>

Answer ā„–2

Here is an example of how you can achieve this:

const buttons = document.getElementsByClassName("button");
let count = 0;
const display = document.getElementById("display");

for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", function() {
    buttons[i].classList.toggle("active");

    if (this.classList.contains("active")) count++;
    else count--;

    display.innerHTML = count;
  });
}
.active {
  background-color: #e68352 !important;
}

.button {
  background-color: #ffffff;
}
<input type="button" id="button1" class="button" value="A" />
<input type="button" id="button2" class="button" value="B" />
<input type="button" id="button3" class="button" value="C" />

<p>
  Button Clicked
  <span id="display">0</span> Times
</p>

The if else statement will increment the count by 1 if the button has the class "active", and decrement it by 1 if it does not.

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

Struggling with TypeScript declaration files has been a challenge for me

I'm encountering an issue with using the trace function in my TypeScript code. The function has been declared in a .d.ts file as shown below: declare function trace(arg: string | number | boolean); declare function trace(arg: { id: number; name: strin ...

Alter the value of a key within a JSON object at a specific nested level using Node.js or JavaScript

I am attempting to swap out a specific value in the JSON file. Let's say the JSON data provided below: sample.json let sample={ "yuiwedw":{ "id":"yuiwedw", "loc": "ar", "body":{ "data":"we got this", "loc":"ar", "system":{ ...

Setting a custom background image in HTML using the designated file PATH

My current issue involves the inability to set my background photo using a CSS file. I am utilizing NetBeans for this project. Inside a folder named css, there is a file called global.css which contains the following code: body{ background-image: url ...

How come the dropdown menu consistently disrupts my CSS design?

Whenever I add a dropdown menu, my CSS layout gets all messed up. Can someone please explain why this happens and how to fix it? Below is the code snippet: <asp:Label ID="projnamelbl" runat="server" CssClass="editlabels" Text="Project Name"></as ...

A revolutionary chat platform combining HTML, PHP, AJAX, JavaScript, and MySQL technologies

In my search for a straightforward chat application example online, I have come across many options using PHP (index.php) with MySQL and AJAX. However, this is not what I am looking for. I am specifically in need of a simple Peer to Peer and Peer to Group ...

What is the best method to assign the value of a useState variable to a specific field in an array of objects for inserting data in

**I have a billing form that includes product details for the admin to fill out. One field, labeled "BillID", should automatically populate with a default value of 'Bill ID + 1' through a variable. **Below is the code: const [BillIdFetch, setB ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Exploring related models in the MEAN stack journey

Iā€™m currently working on setting up a model association in MEAN framework where an Epic can have multiple Tasks associated with it. I typically create the Epic first and then link it to tasks when creating them. The task data model is structured as follo ...

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

Implementing Click Event to Dynamically Created div using jQuery

I have recently started using JQuery and I am encountering difficulties in binding functions to a dynamically created div. When the user clicks on a button, new divs are added to a container along with a change in the background color of that container. U ...

What are some ways to style CSS for links, such as a login button?

Check out this website You may have noticed the login button with a stylish black background created using CSS. How can I achieve a similar look? Some buttons are PHP statements while others are simple play links. I also need the register, lost password, ...

Multiplying array elements within the Vuex state with the assistance of Socket.io

I have developed an application using Vue and Vuex that connects to a Node/Express backend with Socket.IO to instantly push data from the server to the client when necessary. The data sent to the clients is in the form of objects, which are then stored in ...

Adjustable annotations in flot chart

When creating a flot, I can draw segments by specifying the markings in the options. markings: [ { xaxis: { from: 150, to: 200 }, color: "#ff8888" }, { xaxis: { from: 500, to: 750 }, color: "#ff8888" } ] Now, I am looking to remove these existing m ...

What is the best way to ensure that my grid remains contained within its designated area?

I need to incorporate a grid of 16x16 or 64x64 into my layout without it overflowing. I'm considering using flexbox, but unsure of the implementation process. My goal is to have the grid resize based on the container size rather than exceeding its bou ...

Navigating through the realm of Android development entails understanding how to manage a multi-object function in JavaScript when using

In order to load an HTML page using the webview component and handle its functions, I am faced with a challenge. The HTML page contains a multi-object named (webkit.messageHandlers.adClicked). How can I utilize the webView.addJavascriptInterface() functi ...

Is there a way to modify the hover border effect of a TextField in material-ui?

In Persian language, the text direction is set to rtl. I am looking for a way to adjust this input field to suit my language for the project. Please refer to the following image: Image Link I want to achieve something similar, but I am unsure how to ch ...

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Strange behavior observed with CSS intellisense in Visual Code

While working on a ReactJS project, I noticed that when I opt for the style Jsx Attribute for inline CSS, . CSS intellisense seems to not work or only work after I manually add some fields. However, if I manually type the style attribute without using t ...

Issue with functionality of Bootstrap template generated by Visual Studio 2013

I've set up a new ASP.NET MVC project using the latest Bootstrap 3 template, but I'm encountering an issue. There doesn't seem to be any spacing between the header navbar and the content displayed below by Renderbody(). I've attempted t ...