Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 265
Run Avatar asked May 14 '11 01:05

Run


People also ask

What is the code for background color?

background-color: rgba(255, 255, 255, 0);

How can get background color value in jquery?

click(function() { var color = $( this ). css( "background-color" ); $( "p" ). html( "That div is " + color + "." ); });

What is the HTML tag for background 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.


2 Answers

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/

like image 195
Hussein Avatar answered Oct 11 '22 10:10

Hussein


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; 
like image 39
Nathan Ryan Avatar answered Oct 11 '22 09:10

Nathan Ryan