Background-color hex to JavaScript variable
try this out:
var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.
var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
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];
}
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"
In response to the question in the comments below:
I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks.
I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this:
/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/
Example output:
var d = document.createElement('div');
d.style.backgroundColor = 'rgba( 255, 60, 50, 0)';
/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);
// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]
Conversion from rgb to hex using a variable from background color
You need to extract the 3 values from the rgb(a) string
Note I ignore possible transparency
// RGB to HEX
const componentToHex = c => (+c).toString(16).padStart(2,"0").toUpperCase();
const rgbToHex = (rgb) => {
const [r, g, b] = rgb.split(",");
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b)
};
const getRgb = selector => window.getComputedStyle(document.querySelector(selector), null).getPropertyValue('background-color').match(/(\d+, \d+, \d+)/)[1]
console.log(rgbToHex(getRgb(".nhcp1")));
console.log(rgbToHex(getRgb(".nhcp2")));
console.log(rgbToHex(getRgb(".nhcp3")));
console.log(rgbToHex(getRgb(".nhcp4")));
console.log(rgbToHex(getRgb(".nhcp5")));
.nhcp4 {
background-color: teal
}
.nhcp5 {
background-color: rgba(211, 0, 211, 0.5)
}
<div class="nhcp1" style="background-color:red">Div 1</div>
<div class="nhcp2" style="background-color:blue">Div 2</div>
<div class="nhcp3" style="background-color:green">Div 3</div>
<div class="nhcp4">Div 4</div>
<div class="nhcp5">Div 5</div>
Set HTML Background Color as JS Variable
You can use JavaScript to set the background color instead of trying to use a JavaScript variable in the HTML, as that is not possible:
var colour = "blue";
document.body.style.backgroundColor = colour;
How to get hex color value rather than RGB value?
var hexDigits = new Array
("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
//Function to convert rgb color to hex format
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}
(Source)
for loop print same hex color as background color
You could clean it up a bit and use the same color for the background color too.
function returnMe() { var content = ""; for (var i = 0; i < 5; i++) {
var color = '#' + (function co(lor){ return (lor += [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)]) && (lor.length == 6) ? lor : co(lor); })(''); content += "<a class='a' href=''>"; content += "<span class='b'>"; content += color + "</span>"; content += "<span class='c' style='background: "+ color +"'></span>"; content += "</a>"; } document.getElementById("clr").innerHTML = content;}
returnMe();
.a { display: inline-block; background: #fff; border: 1px solid #e2e2e2; width: 180px; height: 180px; margin: 10px; text-align: center}
.b { background: #f9f9f9; display: inline-block; width: 100%; padding: 10px 0}
.c { display: inline-block; width: 100%; height: 141px}
<div id="clr"></div>
Set Background Color using HEX
I would suggest .attr( attributeName, function ) and CSSStyleDeclaration.removeProperty() instead to use a regex:
$("div").attr('style', function() { this.style.removeProperty('color'); // remove color if exist.... return this.style.cssText + 'color:#3282c3;'; // add your color});$("div").each(function() { console.log(this.outerHTML);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div style="font-family: Helvetica;line-height: 100%;margin-top: 20px; text-align: left;vertical-align: bottom;color: blue"> I want a hex color! (I have already a style prop...)</div><div> I want a hex color!</div>
Related Topics
Unique Object Identifier in JavaScript
Is 'Window' Really Global in JavaScript
Where Should Ajax Request Be Made in Flux App
Differencebetween Using Constructor VS State = {} to Declare State in React Component
Dynamic Variables Names in JavaScript
Accessing the Content of Other Tabs in a Browser
What's the Yield Keyword in JavaScript
How to Load the Web Page Content Based on User Scrolling
Jquery .Find() Doesn't Return Data in Ie But Does in Firefox and Chrome
Get Content of a Div Using JavaScript
Changing the Default Title of Confirm() in JavaScript
How to Remove Leading and Trailing White Spaces from a Given HTML String
JavaScript Es6 Cross-Browser Detection
How to Read a Text File from Server Using JavaScript
Fetching Values from Email in Protractor Test Case
Typescript Compile to Single File