Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get color of DIV in hex format JQuery

This is my code:

function getTraits(trait) {
    $("#"+trait).on("click", function() {
        alert($(this).css('backgroundColor'));
        if (toHex($(this).css('background-color')) != highlightedColor) {
            $("#"+trait).css("background-color", highlightedColor);
            // If the element isn't highlighted, highlight it.
        } else {
            $(this).css("backgroundColor", defaultColor);
        }
    })
}

I am trying to toggle a highlight on a div on the user's click. I would like to get the background color of the div because it would be inefficient to store a boolean toggle for each and every div. So I want a toHex(rgb) function. I saw a lot of those on SO, so I tried using them and none of them worked. The alert() I put to show me the format JQuery was returning gave me rgba(0,0,0,0). I attempted to modify a regex I found like this:

var rgb = rgb.match(/^rgba((\d+),\s*(\d+),\s*(\d+))$/);

That failed to work with a TypeError: rgb is null.

Thanks for any help you can give me!


1 Answers

I know, not the answer to your question, but have you considered jQuery's toggleClass() option?

Define a highlighted CSS class:

DIV.default { background-color: whitesmoke; }
DIV.highlighted { background-color: yellow; }

and then when the user clicks your DIV:

function getTraits(trait) {
    $("#"+trait).on("click", function() {
        // Toggle both classes so as to turn one "off" 
        // and the other "on"
        $(this).toggleClass('default');
        $(this).toggleClass('highlighted');

        // Ensure we have at least one class (default)
        var hasOne = $(this).hasClass('highlighted') || $(this).hasClass('default');
        if (!hasOne) {
          $(this).addClass('default');
        }
    })
}
like image 153
Forty3 Avatar answered Jan 01 '26 15:01

Forty3