Clicking the button will remove any previously applied CSS style using jQuery

Is there a way to remove the background color that was applied to a previously clicked button when clicking on another button? The current code successfully changes the background color of the clicked button upon hover, but it doesn't reset or remove the styles when switching to another button.

$("button").each(function(){
    var $this = $(this);
    $this.click(function(e) {
        e.preventDefault();
        var color = $this.css('background-color');
        $this.css({'background-color': color, 'color': '#ffffff'});
    })
});
.btn {
  border: 2px solid black;
  background-color: white;
  color: black;
  padding: 14px 28px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
}

.success {
  border-color: #04AA6D;
  color: green;
}

.success:hover {
  background-color: #04AA6D;
  color: white;
}

.info {
  border-color: #2196F3;
  color: dodgerblue;
}

.info:hover {
  background: #2196F3;
  color: white;
}

.warning {
  border-color: #ff9800;
  color: orange;
}

.warning:hover {
  background: #ff9800;
  color: white;
}

.danger {
  border-color: #f44336;
  color: red;
}

.danger:hover {
  background: #f44336;
  color: white;
}

.default {
  border-color: #e7e7e7;
  color: black;
}

.default:hover {
  background: #e7e7e7;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button class="btn success">Test</button>
<button class="btn info">Test 1</button>
<button class="btn warning">Test 2</button>
<button class="btn danger">Test 3</button>
<button class="btn default">Test 4</button>
</body>
</html>

Answer №1

You need to approach this differently; relying on hover color to set the active color is not effective. When navigating the buttons with the keyboard and clicking them using Enter, the background-color does not apply.

A more effective approach would be to use jQuery to add an active class and then adjust the button's color with CSS when it is active.

Here's a suggestion:

$("button").each(function(){
    var $this = $(this);
    
    $this.click(function(e) {
        // reset class of active buttons, if needed
        $("button.active").removeClass('active');

        e.preventDefault();
        $this.toggleClass('active')
    })
});
.btn {
  border: 2px solid black;
  background-color: white;
  color: black;
  padding: 14px 28px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
}

.success {
  border-color: #04AA6D;
  color: green;
}

.success:hover, .success.active {
  background-color: #04AA6D;
  color: white;
}

.info {
  border-color: #2196F3;
  color: dodgerblue;
}

.info:hover, .info.active {
  background: #2196F3;
  color: white;
}

.warning {
  border-color: #ff9800;
  color: orange;
}

.warning:hover, .warning.active {
  background: #ff9800;
  color: white;
}

.danger {
  border-color: #f44336;
  color: red;
}

.danger:hover, .danger.active {
  background: #f44336;
  color: white;
}

.default {
  border-color: #e7e7e7;
  color: black;
}

.default:hover, .default.active {
  background: #e7e7e7;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button class="btn success">Test</button>
<button class="btn info">Test 1</button>
<button class="btn warning">Test 2</button>
<button class="btn danger">Test 3</button>
<button class="btn default">Test 4</button>
</body>
</html>

Answer №2

let previousColor = null;
let previousButton = null;
$("button").each(function(){
    let $this = $(this);
    $this.click(function(e) {
        e.preventDefault();

        if (previousButton != null){
           previousButton.css({ 'background-color' : '', 'color': previousColor });         
        } 
        previousButton = $this;    
        previousColor = $this.css('background-color');
        let color = $this.css('background-color');
        $this.css({'background-color': color, 'color': '#ffffff'});
    })
});
.btn {
  border: 2px solid black;
  background-color: white;
  color: black;
  padding: 14px 28px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
}

.success {
  border-color: #04AA6D;
  color: green;
}

.success:hover {
  background-color: #04AA6D;
  color: white;
}

.info {
  border-color: #2196F3;
  color: dodgerblue;
}

.info:hover {
  background: #2196F3;
  color: white;
}

.warning {
  border-color: #ff9800;
  color: orange;
}

.warning:hover {
  background: #ff9800;
  color: white;
}

.danger {
  border-color: #f44336;
  color: red;
}

.danger:hover {
  background: #f44336;
  color: white;
}

.default {
  border-color: #e7e7e7;
  color: black;
}

.default:hover {
  background: #e7e7e7;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button class="btn success">Trial</button>
<button class="btn info">Trial 1</button>
<button class="btn warning">Trial 2</button>
<button class="btn danger">Trial 3</button>
<button class="btn default">Trial 4</button>
</body>
</html>

Answer №3

To achieve this effect using only CSS, you can include the focus pseudo-class along with the hover pseudo-class in your CSS to change the color upon interaction:

.btn {
  border: 2px solid black;
  background-color: white;
  color: black;
  padding: 14px 28px;
  font-size: 16px;
  cursor: pointer;
  border-radius: 5px;
}

.success {
  border-color: #04AA6D;
  color: green;
}

.success:hover,
.success:focus {
  background-color: #04AA6D;
  color: white;
}

.info {
  border-color: #2196F3;
  color: dodgerblue;
}

.info:hover,
.info:focus {
  background: #2196F3;
  color: white;
}

.warning {
  border-color: #ff9800;
  color: orange;
}

.warning:hover,
.warning:focus {
  background: #ff9800;
  color: white;
}

.danger {
  border-color: #f44336;
  color: red;
}

.danger:hover,
.danger:focus  {
  background: #f44336;
  color: white;
}

.default {
  border-color: #e7e7e7;
  color: black;
}

.default:hover,
.default:focus {
  background: #e7e7e7;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button class="btn success">Test</button>
<button class="btn info">Test 1</button>
<button class="btn warning">Test 2</button>
<button class="btn danger">Test 3</button>
<button class="btn default">Test 4</button>
</body>
</html>

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 with PHP and HTML Character Interactions

My variable looks like this: $name=' 18 " LCD TV '; When attempting to use it in an HTML input, the characters after the " do not display. Any suggestions on how to fix this issue? ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

How can I load a URL without causing a page refresh?

While searching around, I stumbled upon this HTML 5 code snippet: window.history.pushState("object or string", "Title", "/new-url"); I started thinking: how can this be implemented? Is there a way to utilize this code to change the URL to without needin ...

Images displaying correctly in Next.js development environment, but failing to load on Github Pages production site

I am currently using Next.js alongside Tailwind CSS and I'm encountering an issue while attempting to set a background image for a specific div. Oddly enough, the image appears to load correctly in development mode, but fails to display when deployed ...

How to continuously animate images in HTML using Bootstrap

I want to showcase 7-8 client images in a continuous loop using a <marquee> tag. The issue is that there is a gap between the last and first images. Here is the HTML code I have: <marquee> <ul> <li><a href="#&q ...

Is being unfazed by work a common occurrence?

After completing a complex cycle that processes data from the database and writes it to an array, I encounter a situation where the array processing function is triggered before the array is fully populated. This forces me to use setTimeout() for proper ti ...

I'm struggling to understand how to insert the JSON response into an HTML element

I am encountering an issue with my code where the response from the API call is not displaying on the HTML page. I'm unsure why it's not showing up even though the page loads successfully. <!DOCTYPE html> <html> <head> <title ...

Finding the precise Time zone with date-fns: A comprehensive guide

I've implemented a date pipe using the date-fns library for formatting dates. Here is the code: date.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { format } from 'date-fns'; @Pipe({ name: 'formatDate ...

Guide to showing a form following a button click in Angular 9

I am trying to create a feature on my page where when I click a button, a form will appear directly below it. Additionally, I would like the number of forms displayed to match the number of times the button is clicked. Being a newcomer to Angular 9, I am ...

Switch the menu state to closed when we click outside of it while it's open

I'm currently working on a scenario involving a menu that toggles when a button is clicked. The issue I'm facing is that when I click on the menu button, it opens correctly. However, the problem arises with the following code: Whenever I click ...

Display or conceal a div depending on the selected radio button

I am attempting to display a hidden div based on the input of a radio button. If the "yes" option is checked, the hidden div should be shown. Conversely, if the "no" option is checked, the div should be hidden. I'm not sure why this code isn't w ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

Tips for successfully retrieving a span value in VUE

I am working with forms <input type="text" v-model="email"> <span>Extracted Value</span> Can someone help me figure out how to pass the value from the span element? data () { return { email: '/*Here goes the extracted valu ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

Adding a clickable button to execute code within a LeafletJS marker!

I'm currently experimenting with adding a button inside a pointer that will log a message to the console. This is simply a test to see if I can execute a method on the marker, but so far I haven't been able to display any text. const marker = L.m ...

Tips for employing the slice approach in a data-table utilizing Vue

I have a unique situation in my Vue app where I'm utilizing v-data table. The current display of data in the table works fine, but I now want to enhance it by incorporating the slice method. Here is the current data displayed in the table: https://i ...

What is the best way to distinguish between various objects that are all in a single line?

After creating an array of objects with data such as name and id, I used the res.json() method to convert it into json format for browser use. However, when I input the array of object data, it looked like this: [ { id: 1, name: 'albany sof ...

Maintaining a reliable and efficient way to update the userlist in a chatroom using PHP, AJAX, and SQL

I've successfully created a chatroom using PHP, JavaScript, AJAX, and SQL without the use of JQuery or any other tools. I maintain user persistence through session variables to keep users visible on the front page of my website (www.chatbae.com). How ...

Exploring ways to loop through objects in a React application

I'm trying to figure out how to modify the code below to iterate through a custom object I have created. function itemContent(number) { return ( <div > <div className="item"> <div className="itemPic& ...