Change the color of a table cell on two consecutive clicks using jQuery

Hey there! I've got this super simple code that does the job of changing the background color of a selected cell in a table to red. It's pretty awesome and works like a charm.

Here's the CSS:

.fixture-table td.team.on {
    background-color: red;
}

And here's the JS:

$(document).on('ready', function() {
    // change the color to red on table when clicked
    $('td').click( function() {
        $(this).toggleClass('on');
    });
});

So, what I'm trying to achieve now is when the cell is clicked once, change it to red. If clicked again, change it to yellow. And then if clicked once more, remove the background color altogether. Essentially, I want to have three different states for the cell.

Thanks a bunch!

Answer №1

A unique approach to enhancing the functionality is by incorporating a data attribute to retain the current state and dynamically changing the classes based on this state.

For more insights, visit: http://jsfiddle.net/NhT92/

$('td').click(function () {
    var cell = $(this),
        state = cell.data('state') || 'first';

    switch (state) {
        case 'first':
            cell.addClass('red');
            cell.data('state', 'second');
            break;
        case 'second':
            cell.addClass('yellow');
            cell.data('state', 'third');
            break;
        case 'third':
            cell.removeClass('red yellow');
            cell.data('state', 'first');
            break;
        default:
            break;
    }
});

CSS

.red {
    background-color: red;
}
.yellow {
    background-color: yellow;
}

Answer №2

Cascading Style Sheets:

.blueColor { background-color:blue; }
.greenColor { background-color:green; }
.noShade { background-color:#f2f2f2; }

JavaScript:

$(document).on('load', function() {

    $('div').click( function() {
        if($(this).hasClass('noShade')) {
          $(this).removeClass('noShade').addClass('blueColor');
        }
        else if($(this).hasClass('blueColor')){
          $(this).removeClass('blueColor').addClass('greenColor');
        }
        else{
          $(this).removeClass('greenColor').addClass('noShade');
        }
    });

});

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

Locate the positions in the array of objects that do not have any objects containing a specific value for a

Currently, I am utilizing Mongoose and my schema looks something like this: var User = new mongoose.Schema({ registrations:[{ fieldA: String, fieldB: String, }] }); var UserModel = mongoose.model('User', User); My objec ...

AngularJS User-Centric Authentication Page

I am in the process of developing an Angular application that will dynamically display data based on user input from the login page. In essence, I require assistance with achieving the following: Upon entering a username and password, the URL should b ...

Can Material UI be utilized to design a Shopify e-commerce store?

As I prepare to create a Shopify storefront for the first time, I have a few inquiries. I have noticed how convenient it is to design both a mobile and desktop view using Material UI, but I have come across conflicting information online. Some sources su ...

How can I determine the transfer speed of a file being uploaded via jquery/Ajax?

As I upload a file using ajax/jquery, you can check out the demonstration here. The function provided will give you the percentage completion status: //progress bar function function OnProgress(event, position, total, percentComplete) { //Progress bar ...

Contrasting float-start and start-0 characteristics

I'm attempting to recreate the layout shown in this image using HTML and Bootstrap 5: https://i.sstatic.net/R6Naf.jpg I'm having trouble with the alignment of the elements. When I use float-start for the image, it aligns properly, but start-0 do ...

Ways to pass an instance variable between different files in Node.JS?

Currently, I am in the process of constructing a Telegram bot and utilizing the npm package found at: https://www.npmjs.com/package/node-telegram-bot-api My project structure looks like this: https://i.sstatic.net/tllMw.png Within my app.js file, I init ...

CORS problem arises when making an Ajax API request

I am attempting to retrieve an API response from Sprout Video using their Javascript API. However, I am encountering a CORS issue with the request. While I can successfully receive a response in Postman, my website is not able to do so. Despite searching ...

Leveraging jQuery alongside HTML5 Video

I have a website that offers live streaming services. I wrote some code specifically for iPads which successfully plays the stream: window.location = 'http://<?php echo DEVSTREAMWEB; ?>/<?php echo $session_id;?>/'+camerahash+'/p ...

The SVG image created is not appearing on the screen

I'm working on a JavaScript project to display SVG elements, but I'm encountering an issue with the "image" element. For some reason, when I create the image element dynamically, it doesn't appear in the browser. However, if I manually copy ...

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

How to retrieve a value from an array using a specific name rather than a numerical key

After creating an object and adding an asset b345 with some properties in it, such as: asset = []; asset.push({'b345' : { 'prop1':'value 1', 'prop2': null}}); I aim to dynamically add more assets later into the sa ...

Retrieve the JSON array embedded within the JSON string

Can someone help me extract the JSON array from a JSON string? I've been struggling to make it work. Here is the code snippet for reference: // I need assistance with this var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789" ...

What methods can I use to prevent caching of XMLHttpRequest requests without relying on jQuery?

I am currently working on a web application that refreshes a table every minute from an XML file. However, I have noticed that when I make edits to the content of the XML file, I see a "304 Not Modified" message in the script log when trying to retrieve th ...

When the affirmative button is clicked, apply a border and background color

I am in the process of creating custom text boxes for user comments. I need help with adding borders and background colors to a box when the user clicks on the YES button, in order to visually indicate which box the click originated from. Can anyone assis ...

I am looking for a way to implement the :active state on external controls for jcarousel

I am currently using a Jcarousel and I need to assign the class "active" to the current pagination option. I have come across similar inquiries regarding this matter. <script type="text/javascript"> /** * The initCallback callback is used * to add ...

Changes made in the DropDownList selection are not being accurately captured on the server side

I have come across an issue with a dropdownlist in my asp.net web page. This dropdownlist is a server-side control. I am making an ajax call and within that call, I am adding a new item to the dropdownlist and setting it as selected. The new item displays ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

jQuery blur unless

I would like to implement a feature where a div is hidden when a text box loses focus, except if the user clicks on a specific div. If the user clicks on that particular div, then the action of losing focus should not trigger the hiding of the div with cla ...

When I incorporate a gradient, the background of my Bootstrap button flickers when clicked

I have implemented Bootstrap 4 with the following code snippet: <!-- Flickers on click --> <a href="javascript:void(0)" class="btn btn-primary">.btn .btn-primary</a> <!-- Does not flicker on click --> <a href="javascript:void(0 ...

Converting an HTML table into a multi-series chart

Is there a way to automatically convert an HTML table into a multi-series chart using JavaScript or jQuery? Here is a sample of my table: | Category | YYYY | YYYY | YYYY | | Asset | 1,500.00 | 3,590.00 | 5,000.00 | | Revenue | 2,560 ...