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
background-color: rgba(255, 255, 255, 0);
click(function() { var color = $( this ). css( "background-color" ); $( "p" ). html( "That div is " + color + "." ); });
The attribute is used with the HTML <body> tag, with the CSS property background-color. HTML5 do not support the <body> tag bgcolor attribute, so the CSS style is used to add background color. The bgcolor attribute deprecated in HTML5.
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/
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;
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