What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, which is not what I intended. My goal is to cycle through at least 5 different classes (or even more) each time the button is clicked. Unfortunately, I have been unable to find a solution to achieve this desired functionality.

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <script>
    $(document).ready(function () {
      $("button").click(function () {
        $(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
      });
    });
  </script>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" class="btn btn-success">Random button</button>
  </body>
</html>

Answer №1

To apply multiple classes to an element, you can create an array that holds all the classes and keep track of the index of the currently applied class using a variable or jQuery's .data() method.

Then, on button click event, you can retrieve the current index, increment it to get the next class from the array, and apply it to the button. Here's how you can do it:

$(document).ready(function () {
    var classes = ['btn-success', 'btn-info', 'btn-primary'];

    $("button").click(function(){
        let idx = $(this).data('class-index') ?? 0; // index of current class
        let cls = classes[idx+1] ?? classes[0]; // get the next class
        $(this).data('class-index', classes.indexOf(cls)); // store the new class index
        $(this).removeClass(classes).addClass(cls); // remove old class and add new one
    });
});
button { outline: none!important; }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<button id="p" class="btn btn-success">Random button</button>

Answer №2

Each click of the button can trigger an increase in a counter value, which then determines the color class to be added based on the count. For example, a count of 0 corresponds to green and a count of 1 corresponds to red. It's important to note that the toggle function is specifically designed for toggling between two states similar to how a physical toggle switch works.

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

Iterate through three images using the `background-image` property in my Div

Is there a way to modify a code that loops through images based on an Img source in order to work with the "background-image" property of a div? HTML <div id="section2"></div> CSS #section2 { background-image: 'url(..images/banner1.jp ...

Having difficulty retrieving data with ajax in a spring boot application

I am encountering issues passing and fetching data from a form in the Spring Boot API. I am not receiving any response, so I would appreciate it if someone could review my code and provide a solution, please. <!DOCTYPE html> <html> <head> ...

Pass the code from the webpage to the PHP script

On my website, I have implemented a feature using JavaScript that dynamically changes the page content. Now, I am looking for a way to send this updated content to a PHP script. How can I achieve this functionality? ...

Guide to Displaying Items in Order, Concealing Them, and Looping in jQuery

I am trying to create a unique animation where three lines of text appear in succession, then hide, and then reappear in succession. I have successfully split the lines into span tags to make them appear one after the other. However, I am struggling to fin ...

jQuery Put function failing to execute, yet successfully running with postman

I hate cluttering up Stackoverflow with these messy questions, but after hours of searching for examples, I couldn't solve the issue. Let me explain. I'm attempting to use jQuery to PUT data, and here's my code: $.ajax ({ type: "PUT", ...

Compose an abbreviated version of the function

I am facing an issue with a function that involves calling out specific states with similar lines of code. Below is the function in question: DoThis(type) { if (type === 'a') { this.setState({ activeA: { display: 'block', opac ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

What is the process for incorporating a dropdown field and editable field within a container?

Looking to create a unique setup by incorporating dropdown fields and editable text fields within a designated box, similar to the image provided. Any tips on how to successfully implement this design? https://i.sstatic.net/6tGMp.jpg ...

Is it feasible to exclude certain CSS files in an HTML Master page within the .NET framework?

On my website, I have 6 CSS files linked, but on a specific page, I only need to use 3 of them. Our developers are using a master page in .NET and are hesitant to make changes to it. Therefore, I am wondering if there is a way to exclude certain linked C ...

Steps for duplicating a .clone() jquery object

Having issues reusing or storing an element with checkboxes using jquery's .clone() function. Here's an example: $('.test1').on('change', ':input', function() { $temp = $(".test1").clone()[0]; $('#test2&a ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

JS Function created to supply elements to React component is failing to return correctly

Trying to validate a dataset by checking for specific prefixes or suffixes in a string, and then breaking the string into <span> elements. The current function correctly identifies the relevant morphemes in the data set, but fails to return the split ...

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

Leverage Next.js routing in plain JavaScript without relying on React hooks

I am working on a NextJS app and I need to implement a function that can redirect to any page using Next.js routing. For example, after a user completes the signup process, I want them to be redirected to a specific page. So, I tried creating a reusable ...