How can I switch between different bootstrap button classes when clicking on them?

Looking to add some flair to my Bootstrap buttons by changing their color when clicked. The goal is for the button to go from gray (btn-default) to green (btn-success) with each click, and then back to its default state on the next click. I attempted to achieve this with an if statement, but it seems to change color only once and doesn't revert to the original class upon subsequent clicks.

$("#critical_btn").click(function () {

    if (this.class= 'btn-default'){
        $('#critical_btn').removeClass('btn-default').addClass('btn-success ');
        $(this).addClass('btn-success').removeClass('btn-default');
    }
    else if (this.class= 'btn-success'){
        $('#critical_btn').removeClass('btn-success').addClass('btn-default ');
        $(this).addClass('btn-default').removeClass('btn-success');
    }
});

I'm still getting the hang of this, so any advice or pointers would be tremendously helpful!

Answer №1

Rather than utilizing an if-else statement, you can toggle between two classes by using $(selector).toggleClass('firstclass secondclass'), provided that one of them is already designated in the HTML markup. (http://api.jquery.com/toggleclass/)

The jQuery code would appear as follows:

$("#critical_btn").click(function() {
  $(this).toggleClass('btn-default btn-success');
});

For a demonstration, refer to this example:

https://jsfiddle.net/xsotp27s/

Answer №2

To achieve this behavior, you can utilize the hasClass Method :

$(document).ready(function() {

     $("#critical_btn").click(function () {

         if ($(this).hasClass('btn-default')){
             $('#critical_btn').removeClass('btn-default').addClass('btn-success');
             $(this).addClass('btn-success').removeClass('btn-default');   
         }

         else if ($(this).hasClass('btn-success')){
             $('#critical_btn').removeClass('btn-success').addClass('btn-default');
             $(this).addClass('btn-default').removeClass('btn-success');
         }

     })
 })

Here is the final code:

<!DOCTYPE html>
<html>
<head>
    <style>
        .btn-success {background-color: red}
        .btn-default {background-color: blue}
    </style>
</head>
<body>
    <button id="critical_btn" class="btn-default">Button</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
     $(document).ready(function() {

         $("#critical_btn").click(function () {

             if ($(this).hasClass('btn-default')){
                 $('#critical_btn').removeClass('btn-default').addClass('btn-success');
                 $(this).addClass('btn-success').removeClass('btn-default');   
             }

             else if ($(this).hasClass('btn-success')){
                 $('#critical_btn').removeClass('btn-success').addClass('btn-default');
                 $(this).addClass('btn-default').removeClass('btn-success');
             }

         })
     })
    </script>
</body>
</html>

Answer №3

Simply switch between classes using the following method:

$("#important_button").click(function () {
   $(this).toggleClass('btn-primary btn-danger'); 
});

Answer №4

$("#urgent_button").on("click", function() {
   $(this).toggleClass("active inactive");
});

If you need to switch between two classes in jQuery, the toggleClass method is your solution!

For more information, visit http://api.jquery.com/toggleclass/

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

Issue locating the bottom of the scroll bar

My attempt to detect when the scroll reaches the bottom of a div involves using this code: $('.scrollpane').scroll(function(){ if ($(this).scrollTop() + $(this).height() === $("#results").height()) { alert('scroll at bottom&a ...

Troubleshooting Media Query problem in Angular 6

Currently, I am developing a website using Angular 6. One of the components in my project is called our-work.ts. To set its media query globally, I decided to define it in a file named global.scss. Here's an example snippet of what I've written: ...

Selenium failing to input text into field

My goal is to extract data from the following URL: There are three key components to this extraction: Choosing the correct game type under "Valitse peli" I want to select "Eurojackpot" for this. Setting the date range using variables. Currently, I hav ...

Mastering Ajax techniques for uploading multiple files

I'm in need of assistance - I have devised a straightforward form that empowers users to upload comment text and files onto the server. The 'upload.php' file handles the file upload process flawlessly but only for one file at a time. My goa ...

What are the Functions of Ctrl-K on Stack Overflow?

I'm intrigued by how to incorporate the Ctrl+K (code sample) feature for code. For example: public static void main(String args[]){ System.out.println.out("welcome"); } Is there a way to nicely format this? Do we need any specific package to ...

The TinyMCE editor is experiencing difficulty with editing the textarea

Having an issue with my PHP submission page. I have a form with various fields, including a textarea that uses TinyMCE. I also have an option to duplicate the existing form. The problem is, I can't edit the duplicated second editor - it shows up in th ...

How to retrieve the hidden parameter value stored within a div element with jQuery

Within the mainDiv, there is a hidden field with the class name "myHiddenField". I am looking to retrieve the value of this hidden parameter by using jQuery. I attempted: $("#mainDiv .myHiddenField").val() as well as $("#mainDiv .myHiddenField").attr( ...

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

Scrapy and xpath not functional - solely relying on css for operation

Attempting to scrape data from this website: After retrieving all elements using the following code: products = response.xpath("//ul[@class='products']//ancestor::li") I attempted to extract prices for all elements in the scrapy shell ...

Showcasing pictures with a prominent large image accompanied by two smaller ones on the right side

In my use of Material-ui-next, I am attempting to create images in a specific layout. ------ --------- | | | | 2 | | | | 1 |---| | | | | 3 | ------ --------- I have encountered some unusual issues. 1 - 3 appears below 1 ...

Utilize CSS to display metadata above the text

Is there a way to visually represent parts of speech data in CSS for text that has been tagged with such classifications? Take the sentence Ten pins were set in order., which, when parsed using Spacy, results in: token pos 1 Ten NUM 2 pins NOUN 3 ...

Floating TDs table after four consecutive columns

I am in need of a table that will consist of 4 TDs in each row and then automatically move to a new row. In the HTML, I prefer only listing the TDs because I plan on adding more cells constantly and require them to stay in alphabetical order without having ...

Is it feasible to relocate an embedded swf file from one tag to another?

My HTML contains two containers for embedded swf files: <div id="player1"></div> <div id="player2"></div> If I load an embedded video into the first div (player1) like this: swfobject.embedSWF("someURL","player1"); Is it possibl ...

Unable to access post data in Code Igniter through a JQuery Ajax request

Utilizing AJAX for a dynamic filtering feature, my approach involves extracting data from filter fields in the code and transmitting it to the Controller via an AJAX request. Upon receiving the data, I proceed to update the table accordingly. The followin ...

Exploring the functionalities of handler in ASP.NET MVC along with autocomplete features

Is it possible to modify the path triggered by the autocomplete function or adjust the path syntax within a .cshtml view file? For example, consider the following code snippet: Autocomplete Textbox: <form class="form-inline" id="formFilters" runat="s ...

What is the best way to rearrange a sidebar column to be positioned between central content columns on a mobile

I am looking to design a layout with the following components: Left Sidebar Main Content Right Sidebar Extra Content My goal is to achieve the following: On larger screens: Ensure that the "Extra Content" aligns directly below the main content with the ...

How can I center a <a> vertically within a list that has varying heights?

Help Needed: Alignment Issue with Anchor Tags in List I am facing a challenge with vertically aligning the anchor tags inside my list. The number of list items varies based on the pages of my website, so I have used display flex on the list and flex: 1 on ...

The ngFor directive in Angular2 consistently collapses the identical <tr> element

Greetings, I am a newcomer to the world of web development. Recently, I used the *ngFor directive in Angular to generate multiple rows with collapsible details. However, when I click on a row, it always collapses the same div, instead of the corresponding ...

Using jQuery, select a single ID from a div

I have a div with multiple IDs that I need to extract separately and send them to a PHP file. Sending both variables individually seems like the simpler option, but alternatively, I could split the IDs on the server side using PHP after they are sent by jQ ...