How can I get the CSS attributes with jQuery?

I’m writing a cool jQuery snippet where I will need to get the value of the background color and font color from an element’s style rules.

I tried this and it’s not doing anything: var CSSbackground = $(‘.submit-btn’).css(‘background’);

I just want to get the current values so I can manipulate it dynamically. (Ultimate is to invert them on hover). I know how to accomplish the rest; but getting the current values is stumping me (Yes, I have been googling all morning).

Because that’s only using the values assigned through the style attribute/property. CSS assigned through CSS selectors is not covered by that.

That’s actually not true, it returns the computed styles. @marianstevens what do you mean with it’s not doing anything? What is the exact value of CSSbackground when you log it to the console?

I revisited my jsfiddle and got it to return the values in rgb…I’d rather it return the colors in hex, not sure how to do this quite yet. Here’s a link to my fiddle:

You can convert a number through the Number object’s toString() method:

254 .toString(16) // "fe"
1 Like

Okay I have gotten that part to work - I am not sure how to select the pseudo hover class. The idea of this whole thing is to invert the font and background colors on the hover event. (I thought I had this). What direction should I be going in?

Why actually convert the values to hex to do this? You can also invert a colour using RGB like so:

function invertRgb (rgbString) {
  var rgb = rgbString.match(/(\d+),\s*(\d+),\s*(\d+)/)

  return 'rgb(' +
    (255 - rgb[1]) + ', ' +
    (255 - rgb[2]) + ', ' +
    (255 - rgb[3]) +
  ')'
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.