Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background color in hex

Tags:

javascript

How to set elements background color as hex value in JavaScript? backgroundColor method sets only in rgb.

square.style.backgroundColor = input_color; input_color is #123456, but in the source sets rgb(18, 52, 86)

like image 894
Kin Avatar asked Dec 04 '12 21:12

Kin


3 Answers

If you want to get the color of an element which is in rgb format then you can convert it from rgb to hex format

function rgbToHex(col)
{
    if(col.charAt(0)=='r')
    {
        col=col.replace('rgb(','').replace(')','').split(',');
        var r=parseInt(col[0], 10).toString(16);
        var g=parseInt(col[1], 10).toString(16);
        var b=parseInt(col[2], 10).toString(16);
        r=r.length==1?'0'+r:r; g=g.length==1?'0'+g:g; b=b.length==1?'0'+b:b;
        var colHex='#'+r+g+b;
        return colHex;
    }
}

Call the function

var col=document.getElementById('myDiv').style.backgroundColor;
alert(rgbToHex(col)); // alerts hex value

Here is an example.

like image 62
The Alpha Avatar answered Sep 18 '22 15:09

The Alpha


A better solution to your problem would be just to set the background color like this

square.style.backgroundColor = "rgb(12,34,56)";

Otherwise I would use Sheika's example

like image 23
pandavenger Avatar answered Sep 17 '22 15:09

pandavenger


Found something that should work:

document.getElementById('square').attributes['style'].textContent='background-color:'+ input_color 
like image 42
Domotor Zsolt Avatar answered Sep 21 '22 15:09

Domotor Zsolt