How to get the background color code of an element in hex?
Asked Answered
P

8

75

How do I get the background color code of an element?

console.log($(".div").css("background-color"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div" style="background-color: #f5b405"></div>

What I want

#f5b405
Practicable answered 14/5, 2011 at 1:15 Comment(3)
What are you wanting to do with the value?Simultaneous
I want to animate the background colour - $(this).animate({ backgroundColor: '#f5b405' }, 'fast');Practicable
But I just found out that I can use the rgb code to animate the background colour too! lolPracticable
M
106

Check example link below and click on the div to get the color value in hex.

var color = '';
$('div').click(function() {
  var x = $(this).css('backgroundColor');
  hexc(x);
  console.log(color);
})

function hexc(colorval) {
  var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  delete(parts[0]);
  for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
  }
  color = '#' + parts.join('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='div' style='background-color: #f5b405'>Click me!</div>

Check working example at http://jsfiddle.net/DCaQb/

Meredithmeredithe answered 14/5, 2011 at 2:37 Comment(3)
Sometimes $(this).css('backgroundColor') returns rgba(n, n, n, n).Meniscus
Played around a bit with your function to automatize design modernization and such... Example usage scenario jsfiddle.net/DCaQb/625 - not perfect but maybe it helps somebody so I link it here for referenceDemmer
Thanks for this code example. Might want to just rewrite that hexc function as a real function that returns the string though instead of setting a global variable.Bethought
P
11

There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;
Puiia answered 14/5, 2011 at 1:45 Comment(1)
i believe this one is the best approach for new html5 browsers :)Katerine
A
9
function getBackgroundColor($dom) {
    var bgColor = "";
    while ($dom[0].tagName.toLowerCase() != "html") {
      bgColor = $dom.css("background-color");
      if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
        break;
      }
      $dom = $dom.parent();
    }
    return bgColor;
  }

working properly under Chrome and Firefox

Aril answered 8/5, 2014 at 9:19 Comment(0)
G
5

You have the color you just need to convert it into the format you want.

Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/

Gibe answered 14/5, 2011 at 1:18 Comment(0)
A
5

In fact, if there is no definition of background-color under some element, Chrome will output its background-color as rgba(0, 0, 0, 0), while Firefox outputs is transparent.

Aril answered 8/5, 2014 at 14:22 Comment(0)
M
4

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405
Manson answered 2/3, 2018 at 6:32 Comment(0)
I
2

Adding on @Newred solution. If your style has more than just the background-color you can use this:

$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]
Inspirit answered 4/2, 2019 at 15:2 Comment(1)
I like this wayManson
S
1

This Solution utilizes part of what @Newred and @Radu Diță said. But will work in less standard cases.

 $(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');

The issue both of them have is that neither check for a space between background-color: and the color.

All of these will match with the above code.

 background-color: #ffffff
 background-color:      #fffff;
 background-color:#fffff;
Soke answered 11/3, 2019 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.