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!
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');
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With