Update Button Colour upon clicking the Button

I have multiple buttons lined up in a row on my webpage. I want the button's color to change when I click on them. Below is a snippet of my code:

$( "button.change" ).click(function() {
  $(this).toggleClass( "selected" );
});
.Button {
    font-family: Calibri, sans-serif;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: white
}
.selected {
    color: white;
    background:green
}
button#cssColorChange:active{
    color: white;
    background:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>

This code works fine, but currently each button changes color when clicked. I want only the clicked button to change its color, while others remain unchanged.

Answer №1

Is this the kind of thing you're looking for?

$( "button.change" ).click(function() {
  $( "button.change.selected" ).removeClass("selected");
  $(this).toggleClass( "selected" );
});
.Button {
    font-family: Arial, sans-serif;
    font-size:14px;
    font-weight: bold;
    width: 180px;
    height: 30px;
    background:lightgrey;
    color: black
}
.selected {
    color: black;
    background:lightgreen
}
button#cssColorChange:active{
    color: black;
    background:pink
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>

Answer №2

To implement the desired functionality, it is necessary to remove the selected class from all buttons (to clear the styling of any previously selected button) and then apply it to the clicked button. Each button should have a unique ID or none at all, as the class is sufficient for this purpose. Additionally, the buttons should be spaced out using CSS rather than double line breaks.

$("button.change").click(function() {
  $(".change").removeClass('selected');
  $(this).addClass( "selected" );
});
.Button {
    font-family: Calibri, sans-serif;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background: grey;
    color: white;
    display: block;
    margin: 1em;
}
.selected {
    color: white;
    background: green;
}
button#cssColorChange:active{
    color: white;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="Button change">Click to change color</button>
<button class="Button change">Click to change color</button>
<button class="Button change" >Click to change color</button>
<button class="Button change">Click to change color</button>

Answer №3

Consider using this alternative JQuery script

$( "button.change" ).click(function() {
  $('button').removeClass( "active" );
  $(this).toggleClass( "active" );
});

The above code snippet removes the .active class from all buttons and then adds the class only to the button that has been clicked.

Answer №4

If you're looking to enhance the functionality of disabling the button when it's clicked again, check out the example below:

$( "button.change" ).click(function() {
  $(this).toggleClass( "selected" );
$("button.selected").not(this).removeClass("selected")
});
.Button {
    font-family: Calibri, sans-serif;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: white
}
.selected {
    color: white;
    background:green
}
button#cssColorChange:active{
    color: white;
    background:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="Button change" id="">Click to change color</button>
<br><br>
<button class="Button change" id="">Click to change color</button>
<br><br>
<button class="Button change" id="">Click to change color</button>
<br><br>
<button class="Button change" id="">Click to change color</button>

Answer №5

<button id="clickMeButton" onclick="modifyColor()">Modify Background</button>;

<script>;
    var clickMeButton = document.getElementById("clickMeButton");
    function modifyColor(){
        clickMeButton.style.backgroundColor = "blue";

    };
</script>;

Answer №6

It is important to ensure that each element has a unique id assigned to it, as using the same id for multiple elements can cause issues.

$('button.change').click(function() {
  $(this).toggleClass('selected');
})

By the way, your code is functioning correctly. Here's the link to the working example: https://jsbin.com/kodaxiyale/edit

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

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...

Utilizing PHP loops with the integration of a Datetimepicker

When using datetimepicker javascript for bootstrap, I encountered an issue where the instance works fine if there is only one input field or if it's the first of multiple fields. However, when there are multiple fields, the datetimepicker does not wor ...

"Error 404: Invalid request encountered while using React and

I am encountering an issue with a 404 not found error when I attempt to send a post request in React. My code involves using Django Rest Framework on the backend and React Axios on the frontend, but I am facing errors while making the post request. Below i ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...

Ordering BufferGeometries in Three.js for Accurate Rendering

After consulting the discussion on the previous inquiry, I have been working on constructing models in BufferGeometry and have come to understand that the transparent flag plays a role in the rendering order: objects with transparent materials will be rend ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

Ngrx/effects will be triggered once all actions have been completed

I've implemented an effect that performs actions by iterating through an array: @Effect() changeId$ = this.actions$.pipe( ofType(ActionTypes.ChangeId), withLatestFrom(this.store.select(fromReducers.getAliasesNames)), switchMap(([action, aliases ...

Node.js Middleware Design Pattern: Connectivity Approach

I am embarking on a journey to learn Javascript, Node.js, Connect, and Express as part of my exploration into modern web development stacks. With a background in low-level networking, diving into Node.js' net and http modules was a smooth process for ...

Tips for changing the color of shapes when hovering over an image state

I have arranged three images in a column and applied column-count: 3; along with setting border-width for those images. Now I am curious about how to create the hover state for these images. Here is the HTML code snippet: <div class="wrap"> < ...

Position the second line of text to align in MUI

I am facing an issue with aligning the text on the second line. It should match up with the text on the first line. For reference, you can check out the Codesandbox by CLICKING HERE <Card sx={{ maxWidth: 200 }}> <CardMedia component="i ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...

A guide to designing a responsive flexbox layout with various columns and rows

I need help designing a container that is responsive for both mobile and desktop, resembling the layout shown in this image. The initial HTML structure is as follows, but I can modify it by adding elements or classes if necessary. <div class="conta ...

A comparison of Vue's import paths: exploring the variations

Exploring the world of Vue has been exciting but I'm a bit puzzled by the syntax used for importing different libraries. Take, for instance, this import statement: import Vue from 'vue'; import axios from 'axios'; Where do these r ...

What is the reason for AngularJS's inclusion of a colon at the end of a data object in an $http post

While attempting to utilize angular js $http for sending a post request to elasticSearch, I encounter an "Unexpected token : " Error. Here is a snippet of my code: var request= $http({ method: "post", url: path, accept:"*/*", headers:{"Co ...

Node.js server experiencing delays due to V8 processing constraints

REVISED I am currently running a nodeJS http server designed to handle uploads from multiple clients and process them separately. However, I have encountered an issue where the first request seems to block any subsequent requests until the first one is co ...

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

How to efficiently load 3000 objects in Openlayers using IE8

One of my clients exclusively uses IE8 and is working with an openlayers map. He is trying to load 3000 polygons onto the map, which Chrome and IE9 can handle without any issues. However, IE8 freezes when attempting to load the objects. These objects are c ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...