Alter the color of several buttons with each subsequent click using jQuery

How can I change the button color after clicking it? I have a single button that will change to red on the first click, yellow on the second click, green on the third click, and then become disabled after three clicks.

function updateBtnColor() {
  $('.btn-api').click(function() {
    var $this = $(this),
      $clickCounts = 1;
    if ($clickCounts === 1) {
      $this.addClass('bg-act-red');
      $clickCounts += 1;
    } else if ($clickCounts == 2) {
      $this.addClass('bg-act-yellow');
      $clickCounts += 1;
    } else if ($clickCounts == 3) {
      $this.addClass('bg-act-green');
      $clickCounts += 1;
    }
  });
}
.btn-api {
  display: block;
  margin: 0 auto;
  width: 100px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ddd;
  border-radius: 50px;
  padding: 5px;
  cursor: pointer;
  text-align: center;
  font-size: 12px;
}
.bg-act-red {
  background-color: #c5363a;
  color: white;
}
.bg-act-yellow {
  background-color: yellow;
  color: white;
}
.bg-act-green {
  background-color: green;
  color: white;
}
<span class="btn-api"> Change to In Progress </span>

Answer №1

Shift $clickCounts outside the event handler. Furthermore, there is no necessity for the apiBtn() function since you are utilizing an unobtrusive event handler.

var clickCounts = 1;
$('.btn-api').click(function () {
    var $this = $(this);
    if ($clickCounts === 1) {
        $this.addClass('bg-act-red');
        $clickCounts += 1;
    } else if ($clickCounts == 2) {
        $this.addClass('bg-act-yellow');
        $clickCounts += 1;
    } else if ($clickCounts == 3) {
        $this.addClass('bg-act-green');
        $clickCounts += 1;
    }
});

However, if there are multiple buttons, utilize .data() to store the clicked count with the element.

$('.btn-api')
    .data('clickCounts', 1) //Set default value
    .click(function () {
        var $this = $(this);
        var $clickCounts = $this.data('clickCounts');

        if ($clickCounts === 1) {
            $this.addClass('bg-act-red');
            $clickCounts += 1;
        } else if ($clickCounts == 2) {
            $this.addClass('bg-act-yellow');
            $clickCounts += 1;
        } else if ($clickCounts == 3) {
            $this.addClass('bg-act-green');
            $clickCounts += 1;
        }
        $this.data('clickCounts', $clickCounts);
    });

$('.btn-api').data('clickCounts', 1).click(function() {
  var $this = $(this);
  var $clickCounts = $this.data('clickCounts')
  if ($clickCounts === 1) {
    $this.addClass('bg-act-red');
    $clickCounts += 1;
  } else if ($clickCounts == 2) {
    $this.addClass('bg-act-yellow');
    $clickCounts += 1;
  } else if ($clickCounts == 3) {
    $this.addClass('bg-act-green');
    $clickCounts += 1;
  }  
  $this.data('clickCounts', $clickCounts);
});
.btn-api {
  display: block;
  margin: 0 auto;
  width: 100px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ddd;
  border-radius: 50px;
  padding: 5px;
  cursor: pointer;
  text-align: center;
  font-size: 12px;
}
.bg-act-red {
  background-color: #c5363a;
  color: white;
}
.bg-act-yellow {
  background-color: yellow;
  color: white;
}
.bg-act-green {
  background-color: green;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="btn-api"> Change to on Process </span>
<span class="btn-api"> Change to on Process 2 </span>

Answer №2

If you're looking for another way to tackle this, consider using a neat Switch Statement like the one below:

let $clickCount = 1;

$('.btn-api').click(function() {
  switch ($clickCount) {
    case 1:
      $(this).addClass('bg-act-red');
      $clickCount++;
      break;
    case 2:
      $(this).addClass('bg-act-yellow');
      $clickCount++;
      break;
    case 3:
      $(this).addClass('bg-act-green');
      $clickCount;
      break;
  }
});

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

I am looking to retrieve multiple record IDs in Yii2 and have them checked

Can someone guide me on how to retrieve the record ID from the index for removing selected records using Ajax and Jquery? Below is my form along with the Ajax script, but it doesn't seem to be functioning properly. Any help would be appreciated. ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Is there a way to extract all the content from a webpage's body using BeautifulSoup?

Looking to extract text from a medical document webpage for a Natural Language Processing project using BeautifulSoup, but encountering challenges. The specific website in question is located here: The goal is to capture the entire text body by utilizing ...

center text vertically in HTML list

Here at this festival, you'll find a unique menu on the sidebar. The menu is created using an HTML list with the following structure: <ul class="nav nav-pills nav-stacked"> <li class="active"> <a href="index.html"><i ...

Only apply the z-index style in React rendering when it is specifically set to zero

My goal is to set a dynamic z-index for my components based on the state variables. Currently, it only works when the zindex is set to 0. Here is an example of my array: images:[ ['img1',false,[1,2,3],1,0],// ...

Dealing with 405 Error (Method Not Allowed) in AngularJS Integrating with a WCF

I am currently working on a WCF project where I am trying to integrate my WCF project with an Angular JS application. However, when I run the application, no errors are displayed. On inspecting the developer tools in Google Chrome, I noticed some errors re ...

Resetting form fields once data has been successfully posted to MongoDB

I have successfully set up a form that sends data to a MongoDB database. However, I am facing an issue with refreshing the input fields after the form is submitted without reloading the entire page. After calling the resetBooks() function, it seems like i ...

Locating Substrings with CSS Selectors

Looking for a CSS Selector that can handle varying item numbers like span[label='./cakes/item1/./linkText']. I need one selector that works with any range of numbers. I checked out a tutorial on this but no success. The attempted solution was: ...

How to dynamically modify ion-list elements with Ionic on button click

Imagine having 3 different lists: List 1: bus, plane List 2: [related to bus] slow, can't fly List 3: [related to plane] fast, can fly In my Ionic Angular project, I have successfully implemented the first ion-list. How can I dynamically change th ...

What is the best way to initiate a change event using JavaScript?

I am attempting to enable my 4th checkbox automatically when there is a new value in the textbox (myinput). If the textbox is empty, I want to disable it. Currently, you have to tab out before the change event is triggered. Also, how can I check for an e ...

Updating new objects in Angular using JavaScript Object-Oriented Programming may not be working

Recently delving into OOP in JavaScript while working on an AngularJS website, I encountered a situation where my object methods were only altering the properties within the class, but not affecting the new object itself. //Class Var Item = function() { ...

What is the best way to retrieve the state from within a class method?

I'm having trouble accessing the redux state within this function in order to call Translator.init(data) whenever needed. Despite my efforts, I can't seem to access the state as expected. Since I'm more familiar with functional components th ...

What is the best way to arrange form inputs in a single row?

My form consists of three input boxes. While the first two inputs are single line, the third is a description field with 10 rows set as default. However, for some reason, this third box is not aligned properly with the other two. Please refer to the screen ...

Guide on setting the dropdown's selected index through JavaScript

Is there a way to use javascript to set the selected value of a dropdown? Here is the HTML code I am working with: <select id="strPlan" name="strPlan" class="formInput"> <option value="0">Select a Plan</option> </select> I am ...

javascript if an error occurs, refresh the webpage

Currently, I am inquiring about the most effective method for managing JavaScript errors. Given that my application relies heavily on JavaScript, despite diligent testing efforts, encountering bugs is almost certain. I'm interested in knowing if ther ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

Issue with Plesk Obsidian, IISNode, and Express - application functioning solely in local environment

After setting up my Node.JS + Express.JS application on my server with IISNode and Plesk Obsidian, browsing the page in a browser triggers an error: I have already verified the permissions of the relevant folders and ensured that the "App Identities" have ...

If I use jQuery's ajax method to send a CSV file to my Node.js + Express server, where would the file be stored on the server?

I need help with sending a CSV file from my client to my Node.js and Express server using jQuery's ajax POST method. Once the CSV file reaches the server, I am unsure of how to access it. My objective is to pass the CSV file into my route's middl ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

avoiding accidental click events on child elements

Below is the provided HTML code snippet: <label id="label_authorize_net" for="payment_authorize_net" class="for_guest_and_register"> <strong>Credit Card</strong> <br/> ...