Modify the CSS color attribute interactively by clicking

I have a function that can generate random colors. I would like to utilize this function along with jQuery's toggleClass feature to change the color of a table cell when clicked, and revert it back to its original color if clicked again.

Here is the HTML structure of the table:

<div id="container">
    <table id="table">
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</div>

This is the color generation function in JavaScript:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

Here is how the color assignment to the table cell can be done using jQuery:

$(function(){
    $('td').click(function(){
        $(this).css('background-color', getRandomColor());
    });
});

Answer №1

It is important to note that using 'rgba(0, 0, 0, 0)' for solutions may only work on certain browsers, such as Chrome but not IE. For a more reliable approach, this version retrieves the color from the body element as a reference (although any element with no background-color set will suffice).

To simplify your code, you can create a jQuery extension called toggleRandomColor like so:

var blankColor = $('body').css('background-color');
$.fn.toggleRandomColor = function () {
    if ($(this).css('background-color') == blankColor) {
        $(this).css('background-color', getRandomColor);
    } else {
        $(this).css('background-color', '');
    }
};

Then, you can easily implement it by using the following snippet:

$('td').click(function () {
    $(this).toggleRandomColor();
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/nmav8d3n/4/

Answer №2

To easily change the cell color, simply apply a specific class and then verify it:

$('td').click( function(){

    var $td = $(this);

    if($td.hasClass('color-change')) {
        $td.css('background-color','transparent')
            .removeClass('color-change');
    else {
        $td.css('background-color',getRandomColor())
            .addClass('color-change');
    }

});

Answer №3

It seems like you're looking to change the color of a cell when clicked. If the cell is already colored, then you want to make it white instead?

If that's the case

$( function(){
    var default_background = 'rgba(0, 0, 0, 0)';

    $('td').click( function(){
        var $this = $(this),
            curr_background = $(this).css('background-color');

        if (curr_background === default_background){
            $this.css('background-color',getRandomColor);
        } else {
            $this.css('background-color', default_background);  
        }
    });
});

Check out this jsfiddle for reference: http://jsfiddle.net/qL10e5xd/

Answer №4

Verify the default value and generate a new color, or remove it altogether.

function pickRandomColor() {
     var letters = '0123456789ABCDEF'.split('');
     var chosenColor = '#';
     for (var i = 0; i < 6; i++ ) {
         chosenColor += letters[Math.floor(Math.random() * 16)];
     }
     return chosenColor;
 }

$( function(){
    $('td').click( function(){
        if ($(this).css('background-color') == 'rgba(0, 0, 0, 0)') {
            // jQuery returns 'rgba(0, 0, 0, 0)' if background-color is not set
            $(this).css('background-color', pickRandomColor);
        } else {
            $(this).css('background-color', '');
        }
    });
});

http://jsfiddle.net/nmav8d3n/

Answer №5

Feel free to utilize this snippet of code

$( function(){
    var selected = false;
    $('td').click( function(){
    if(!selected){
            $(this).css({'background-color',getRandomColor});
            selected = true;
    }
    else{
            $(this).css({'background-color','white'});
            selected = false;
        }
    });
});

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

Laravel is failing to send a response when trying to pass a PHP variable using Ajax

When I send an AJAX request to the controller, I am receiving a success alert message. View $(".SendEvents").click(function(e){ e.preventDefault(); var ids = $(this).attr("id"); $.ajax({ type:&a ...

Apply the CSS style specifically to the initial row in the table

Is there a way to target the first row of a table with a different tr class using CSS? <div id="right"> <table> <tbody> <tr class="head"> <td >Date</td><td>Info</td><td>More</td> </tr> ...

Loading an AJAX form submission in a replacement page with jQuery Mobile, seamlessly updating my changes

I have set up a jQuery mobile form that initiates an ajax request. The issue I am facing is not with the request itself, but rather with how jQuery mobile reloads the page content upon submission. This causes an error message I added to the current page to ...

Encountering issues with Play Framework's routing system resulting in a 400 bad

I'm currently facing an issue with sending a POST request to the play framework - it seems like this problem could be more related to HTTP than Play itself. $.ajax({ type:'POST', url:'http://localhost:9000/start', data ...

What is the method to reduce the gap between the label and field in Vuetify input controls?

Consider a custom Vuetify text field as an example (Playground) <template> <v-app> <v-container> <v-text-field label="label goes here" variant="plain" density="compact" ...

A commonly used method to adjust the width of a table column to accommodate the size of the child element

I have a specific table width of 776 pixels with three columns. The third column has a fixed width of 216 pixels, but the widths of the other two are unknown. I want the second column to adjust its width based on its content, and whatever space is left aft ...

My HTML Won't Recognize the CSS File

Despite trying various paths and browsers, I am unable to link my CSS file to my HTML file. When inspecting the page elements and checking under resources, the CSS file does not appear. Here is a snippet of my HTML: <html> <head> <meta ...

Difficulty encountered with altering background color of table row in Firefox using CSS

I'm facing an issue with styling table rows that have alternating classes - I want to highlight the row that is being hovered on using CSS. Below is the CSS code I have implemented: .gridrowclass1 { background-color : #bbb00b } .gridrowclass1:h ...

What steps can I take to enhance the responsiveness and overall performance of this code using bootstrap?

Struggling with making your website responsive? No worries, we've all been there. Whether you're a pro at coding in react.js and vue.js or a complete beginner, we all need to start somewhere. Any suggestions or tips on how to improve responsivene ...

Tips for switching back and forth between two classes using jQuery?

I'm having some trouble with the toggleClass function. It doesn't seem to be working correctly for me. The image should toggle between displaying and hiding, but it only changes to hide, not back again. You can view my example here, along with t ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

The network tab is failing to display the CSS styles being applied to the selectors

Being new to markup languages, I encountered an issue when trying to apply my first CSS file to my index.html. Here is how I included the link tag in the HTML file for the CSS file: index.html code Upon checking the network tab in developer tools, I notic ...

Trouble with Unveiling the Secondary Accordion

I am having issues adding a second accordion next to the existing one. Even though the code is working fine in the tryit editor v3.6 online, it doesn't seem to display correctly for me. I have made sure that I am using the latest versions of all scrip ...

The effectiveness of the javascript widget is hindered by the absence of the meta viewport tag,

As I work on creating a widget to appear at the bottom of webpages, I've encountered a styling issue. The widget's display varies based on whether the webpage includes a specified meta viewport tag or not. <meta name="viewport" content="width ...

Locating elements with CSS Selector in Selenium - A complete guide

Currently, my code is set up to access a website and click on each row in the table which then opens a new window. My goal is to extract one specific piece of information from this new window, but I am struggling to utilize CSS selectors to retrieve the f ...

Display/Conceal Title with Hover Effect in Fancybox2

I need assistance with hiding and showing the title in fancybox2 using the hover event. The code I have tried is not working properly. Here is my current code: $("#fancybox-wrap").hover(function() { $("#fancybox-title").show(); }, functio ...

Creating a Dynamic Select Form using PHP, MySQL, and Ajax

Apologies if the title is not clear, but here is my issue. The Problem: I have a dynamic select element that gets its options from an ajax call. I have a function that triggers when the first select element changes. This works well when the user manually ...

Continuously simulate mousewheel events

I'm trying to make my mousewheel event trigger every time I scroll up, but it's only firing once. Can you assist me with this issue? Please review the code snippet below. $('#foo').bind('mousewheel', function(e){ if(e.o ...

Displaying specific choices depending on the previous selection made

I am facing an issue in Laravel where I have two selection options, and one depends on the other. Despite multiple attempts, I haven't been able to resolve it. The database structure is as follows: companies id title channels id company_id title I ...

Having trouble getting the height to work properly on your Blogger Blogspot template?

Issue with embed height=100% not working <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr"> <head> & ...