Creating interactive buttons with CSS and jQuery

As a newcomer to coding, I'm trying my hand at creating two buttons that transition from green to blue with a single click, and eventually incorporating them into a live website.

The functionality I'm aiming for includes:

  1. Both buttons starting off as green. Upon clicking a button, it should change to blue.

  2. If the same button is clicked again, it should revert back to green.

  3. Only one button can be blue at a time. So if a user clicks on button-2 after button-1 is blue, button-1 should turn green and button-2 should turn blue.

While I've managed to implement the first and third features, I'm currently facing challenges with the second one.

Below are the necessary code snippets:

$(document).ready(function () {

    $('#btn1').click(function(){
        $('.btn').css('background-color', 'green');
        $(this).css('background-color', 'blue');

    })

    $('#btn2').click(function(){
        $('.btn').css('background-color', 'green');
        $(this).css('background-color', 'blue');
    })


});
.btn {
    background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/styles.css">

    <title>Document</title>
</head>
<body>
    <button id = "btn1" class = "btn">Button</button>
    <button id = "btn2" class = "btn">Button</button>
    <!--<button id = "btn3" class = "btn" onclick="changeColor()">Button</button>
    <button id = "btn4" class = "btn" onclick="changeColor()">Button</button> -->
    <script src="/jquery-3.6.1.min.js"></script>
    <script src="/index.js"></script>
</body>

</html>

Answer №1

If you want to achieve the desired effect, you can simply toggle a class on the clicked element to change its background color to blue. Simultaneously, this class will be removed from all other buttons.

You can also simplify the code by using a single event handler that is bound to all elements with the class `.btn`, rather than having separate handlers for each element.

jQuery($ => {
  let $btns = $('.btn').on('click', e => {
    let $btn = $(e.target).toggleClass('clicked');
    $btns.not($btn).removeClass('clicked');
  });
});
.btn {
  background-color: green;
}

.btn.clicked {
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>

Answer №2

In my opinion, Rory's solution may be superior, but for those just starting out, this alternative may be easier to grasp (even if it's not as elegant):

$('.btn').click(function(){
  if ($(this).hasClass('clicked')) {$(this).removeClass('clicked');}
  else {$('.btn').removeClass('clicked'); $(this).addClass('clicked');}
});
.btn {
  background-color: green;
}

.clicked {
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <button class="btn">Button</button>
    <button class="btn">Button</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

Struggling to align materialUI input or textfield horizontally

import {Input} from 'material-ui'; import Select from 'react-select'; I've been trying different ways to adjust the margins and padding, even wrapping them in divs, but I can't seem to get Material UI textfield or input alig ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

Create SCSS to style multiple CSS classes

Are there more efficient ways to create css helper classes like the ones shown below? Can I use scss to generate cleaner and better classes? Thank you. .m-1 { margin: 1px !important; } .m-2 { margin: 2px !important } .m-3 { margin: 3px !important } .m-4 ...

Inputting Information into a MySQL Database Using an HTML Form

Hey everyone! I have a simple web form that is supposed to input data into a MySQL database. I wrote some code to check if the connection to my database was working, and it seemed fine. However, when I submitted the form, no data was actually entered into ...

What is the best way to send checkbox values to ActionResult in MVC5?

I am working on an MVC5 application and within my view, I have the following code snippet: <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" }) <div c ...

observing numerous directories in Sass

Is there an efficient way to monitor multiple directories in sass using a shell script? This is what I currently have in my shell script: sass --style compressed --watch branches/mysite/assets/css/sass:branches/mysite/assets/css & sass --style compre ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Concealing tooltip when button is clicked using jQuery

I am facing an issue where the tooltip does not hide on button click. Below is the code for the button in question: <button class="btn btn-outline-inverse ajax_addtocart additems ...

recording JSON requests in expressJS

Update: Apologies for the confusion, I have realized that I needed to move the app.use(express.logger('dev')); higher up in the program. This adjustment has resulted in logging every GET and POST request successfully. Express server now listeni ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

The font styles in IE are failing to render properly following the disabling of caching in Node JS

Why are the CSS fonts not working in Internet Explorer after disabling cache in Node JS? After a user navigates to a page and then clicks the back button to return to the previous page, the font styles are not rendered properly in IE 11. The code 'k ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

The collapse component from bootstrap is not visible due to an overlapping button

I am currently working on a responsive calendar featuring full-width buttons for events, accompanied by additional information displayed using the collapse component below. However, I am facing an issue where the button overlaps with other elements, preven ...

Ways to import JavaScript into child HTMLs embedded within ng-view

I'm diving into angular for the first time and I need to figure out how to incorporate JavaScript into my HTML within ng-view. Some suggestions I came across mention adding jQuery. Can someone provide some guidance on specifically what needs to be ad ...

Color highlighting in dropdown HTML items

I'm trying to create a dropdown menu with alternating colors for the items. Can someone please provide the CSS code needed to style dropdown list items using ODD and EVEN? ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Increase the parent height by 100% when the child element expands

I am attempting to create a full-screen website with 100% height and no scrollbar. I have a div that takes up 90% of the page height and I want to dynamically add elements inside it. However, when there are too many elements inside this div, they expand th ...

conceal a targeted section from the bottom of the iframe

I have a website embedded inside an iframe for use in a webview application. <body> <iframe id="iframe" src="http://www.medicamall.com"></iframe> </body> This is the CSS code: body { margin:0; padding:0; height:10 ...