Ways to permanently alter the color of a button using CSS or jQuery

I am looking to change the color of buttons to blue when they are pressed

$(document).ready(function() {
  $("button.btn.btn-default").on('click', function() {
    $(this).toggleClass('active');
  });
});
.active {
  background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
            $50                              
</button>
<button class="btn btn-default" role="button" value="50">
            $100                               
</button>

My goal is to have one button turn blue (active) at a time, like a radio button. I've tried using jQuery but it's not working as expected. Is there an easier way to achieve this effect?

Answer №1

.css function in jQuery takes a CSS property name and a value as parameters. For instance,

$(this).css('background-color', '#0F89BE')

It does not support adding a new class to an element. To add a class, you should use the addClass method:

$(document).ready(function() {
  $("button.btn.btn-default").on('click', function() {
    $(this).addClass('active');
  });
});
.active {
  background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
            $50                              
</button>

To toggle the class when clicking the button again, you can use toggleClass:

$(document).ready(function() {
  $("button.btn.btn-default").on('click', function() {
    $(this).toggleClass('active');
  });
});
.active {
  background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
            $50                              
</button>

If you only want one button to have the .active class at a time, you can use removeClass on all buttons before adding the class with addClass:

$(document).ready(function() {
  const btns = $("button.btn.btn-default");
  btns.on('click', function() {
    btns.removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
            $50                              
</button>
<button class="btn btn-default" role="button" value="50">
            $60                              
</button>

Answer №2

To modify the color of your button, you have the option to utilize both the css() and addClass() methods in jQuery. The css() method allows you to apply styles directly to the element, while the addClass() method adds a specified class to the element.

$(document).ready(function() {
  // Adding class
  $("button.btn.btn-default").on('click', function() {
    $(this).addClass('active');
  });
  
  // Changing CSS
  $("#css-change").on('click', function() {
    $(this).css('background-color','#0F89BE');
  });
});
.active {
  background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- By Adding Class-->
<button class="btn btn-default" role="button" value="50">
            $50                              
</button>

<!-- By changing css -->
<button id="css-change" class="btn btn-default" role="button" value="50">
            $50                              
</button>

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

Generating a unique bootstrap navigation bar using JSON data to achieve a unique and customized outcome

I have successfully created a bootstrap navbar using JSON data, but I am encountering an issue at one particular point. var data = { "India": [ { "type": "delhi", "link": "https://www.google.com" } ...

Logging into the web application on Google Firebase is simple and secure

I've created a webpage called index.html as the main landing page for my Google Firebase Hosted Web app. This page features input boxes for the user's username and password, along with a button labeled LOGIN. When a user clicks the LOGIN button ...

Is componentDidMount or componentWillMount behaving unexpectedly in your React-Native project?

Could someone please assist me in figuring out what I am doing wrong here? I am attempting to retrieve city data using an API, but neither componentDidMount nor componentWillMount seems to be functioning. I have verified that my getWeather function works ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Click a button to dynamically create a div element with jQuery

Whenever I click the button to add an address, I want to dynamically create a new div structure using jQuery <div id="container"> <div class="address"> <div class="input-reg rb-item input-group"> <sp ...

Adding a background with padding to a bootstrap grid row - here's how!

Bootstrap is a new concept to me, but I am starting to appreciate the grid system it offers. I have successfully created a test layout using Bootstrap, however, the one thing I am struggling with is adding a background around certain rows. Can anyone gui ...

Display numerical ranges on top of the jQuery slider

Hello there! I recently implemented a jQuery slider on my website and now I am looking to add numbers above the slider, kind of like intervals on a ruler. Does anyone know a simple way to achieve this? ...

Ensuring Bootstrap 3 Table Header Widths Remain Fixed

How can I ensure the header columns in my Bootstrap 3 table maintain a fixed width, regardless of the content in the regular rows? I want to avoid the messy look of content splitting onto multiple lines. Here's an example: I'd prefer not to adju ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

Global variable in Npm CLI

I'm working on a CLI tool that heavily relies on storing a unique identifier (uid). I attempted to use fs to store the uid; however, the file was created in the directory where the command was executed. #!/usr/bin/env node const program = require("co ...

How to change the value of feColorMatrix in VueJS

In my Vue Project, I have implemented a component named demo.vue. This particular component features a complex svg within its <template>. When an element is clicked, the Javascript should alter the color of one of the svg's drop shadows. The s ...

Interacting with jQuery and HTML: Revealing sub dvi box content by clicking on the current div box ID

This is my unique jQuery and HTML code. My objective is to display the corresponding sub_box when clicking on box1, box2, or box3. For example: Clicking on box1 should reveal sub_box_1. I have attempted some jQuery code but haven't achieved the desi ...

My custom PHP page designed to insert new records into a MySQL database table appears to be ineffective as it is not updating the table as intended

Firstly, I have confirmed that the const.php file is located in the same directory as the page. I am in the process of developing a web page that enables administrators to add multiple entries to a MySQL table through the website. The functionality involv ...

Tips on specifying a default value when receiving data from an API

I am working with a dropdown list that is populated from an API call. Here is my code snippet: <label>User Code:</label> <select ng-options="c as c.User for c in userList" ng-model="selectedUser" id="search3"> </select> To fet ...

What makes Reactive Extensions stand out as a game-changer?

What makes Reactive Extensions stand out as a game-changer for developers in both .NET and JavaScript? What are the key reasons for developers to dive into learning and implementing them? ...

What is the best way to position two navigation elements to the left and center?

I need the 'a' element to be positioned on the left side of the page and the 'ul' element to be centered. I prefer not to rely on a library or use float: left. Also, applying display: inline; to the ul element is not producing the desi ...

Deactivate the child division by the nth parent division

At the end of my question, I have included a dynamically created div structure with the id "forth-three-one". Now, I need to find a way to disable or hide the input inside this specific div. Directly using the id "forth-three-one" is not an option as it w ...

Displaying or hiding table columns in Vue.js Element-UI el-table based on screen width: a step-by-step guide

Here is my code snippet for generating a table: <el-table :data="tableData" empty-text="No data to display :( " v-if="window.width > 855"> <el-table-column v-for="column in tableColumnsMd" :key=&q ...

Displaying motion of a vehicle with a series of images

Can anyone provide tips on creating an animation that uses multiple images in CSS or jQuery? I was inspired by a Windows skin and would like to create a rotating car animation. Is this possible? Any advice is greatly appreciated. Thank you! ...

Scheduled tasks arranged by the user

My goal is to empower my users to schedule specific actions at their preferred times. With a node server hosted on Azure, I am exploring the potential of using node-schedule for this functionality. One idea I'm considering is running a master schedule ...