Browsers automatically evaluate hex or hsl colors to rgb when setting via element.style.background?
As per the spec:
If the value is translucent, the computed value will be the
rgba()
corresponding one. If it isn't, it will be thergb()
corresponding one.
Meaning that no matter what is your input, the computed value always results in either rgb
or rgba
.
So, answering your question: yes, it is standard behaviour and no, you can't use hex or hsl as it will be computed back to rgba.
Why jQuery replaces hsl() with rgb()?
jQuery has nothing to do with this behaviour - it's simply because browsers render the value in RGB format. You can't change it unfortunately. If you want to get the value in HSL format you need to convert it back from RGB. This question can help you with that, if required.
To prove the above, here's a native JS implementation that exhibits the same behaviour:
[172, 178, 184, 190, 196, 202, 208].forEach(function(backgroundHue) { var span = document.createElement('span'); span.style.backgroundColor = 'hsl(' + backgroundHue + ', 75%, 43%)'; document.querySelector('.add-em-here').appendChild(span);});
.add-em-here span { display: inline-block; height: 40px; width: 40px; border: 2px solid white; margin-left: 6px;}
<div class="add-em-here"> <!-- Added statically - stays with hsl() --> <span style="background-color: hsl(60, 75%, 43%)"></span>
<!-- Added dynamically - auto-replaced with rgb() --></div>
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)
JavaScript: Can't change the selected game mode
There are some issues I see
- Setting background colour via element.style.backgroundColor is going to convert the value you set to rgb/a, so regardless of whether you use hex or hsl you'll end up with rgb(see here).
If you want to keep the method of style you use, you can use setAttribute/getAttribute to set the colour and to get it back to test. - The way you construct your hsl and hex colours looked incorrect(see code changes)
- The
correctColor
variable was not changing, this was because of the closure created by the event listeneters added to the.gameColorOption
divs. I made this variable global to avoid that problem. - Your
randomNumber
code can generate a value of 6 which would be too large to select a.gameColorOption
and would cause an error. UseMath.round(Math.random() * 5)
let selectedGameMode = "rgb";
let correctColor;
gameRunner();
document.querySelectorAll(".colorCodeBtn").forEach((btn) => {
btn.addEventListener("click", () => {
if (btn.classList.contains("selectedColorCode")) return;
btn.parentElement
.querySelector(".selectedColorCode")
.classList.remove("selectedColorCode");
btn.classList.add("selectedColorCode");
selectedGameMode = btn.getAttribute("game-mode");
gameRunner();
});
});
function randomColorGenerator() {
let red = Math.round(Math.random() * 255);
let green = Math.round(Math.random() * 255);
let blue = Math.round(Math.random() * 255);
if (selectedGameMode == "rgb") {
return `rgb(${red}, ${green}, ${blue})`;
} else if (selectedGameMode == "hex") {
let hexRed = red.toString(16).padStart(2, '0');
let hexGreen = green.toString(16).padStart(2, '0');
let hexBlue = blue.toString(16).padStart(2, '0');
return `#${hexRed + hexGreen + hexBlue}`;
} else if (selectedGameMode == "hsl") {
let h = Math.round(Math.random() * 360);
let s = Math.round(Math.random() * 100) + "%";
let l = Math.round(Math.random() * 100) + "%";
return `hsl(${h}deg ${s} ${l})`;
}
}
function gameRunner() {
correctColor = randomColorGenerator();
let randomNumber = Math.round(Math.random() * 5);
document.querySelectorAll(".gameColorOption").forEach((btn) => {
btn.setAttribute('style', 'background-color: ' + randomColorGenerator());
});
document.querySelectorAll(".gameColorOption")[
randomNumber
].setAttribute('style', 'background-color: ' + correctColor);
document.querySelector(".gameQtsColor").innerHTML = correctColor;
document.querySelectorAll(".gameColorOption").forEach((btn) => {
btn.addEventListener("click", (e) => {
if (e.target.getAttribute('style').substr(18) === correctColor) {
document.querySelector(".gameMessage").innerHTML = "Correct!";
document.querySelectorAll(".gameColorOption").forEach((btn) => {
btn.style.backgroundColor = correctColor;
});
} else {
document.querySelector(".gameMessage").innerHTML = "Wrong!";
e.target.style.transform = "scale(1.2)";
e.target.style.border = "4px solid red";
}
});
});
}@import url("https://fonts.googleapis.com/css2?family=Gochi+Hand&display=swap");
body {
background-color: #456064;
}
.navbar {
background-color: #2e4144;
font-family: "Gochi Hand", cursive;
font-size: 28px;
border-bottom: 2px solid #456064;
box-shadow: 0px 6px 16px rgba(0, 0, 0, .3);
}
.navbar-brand {
font-size: 28px;
}
.nav-link:hover {
text-decoration: underline;
}
.colorCodeSelection {
display: flex;
align-items: center;
justify-content: center;
}
.colorCodeBtn:first-child {
border-top-left-radius: 100px;
border-bottom-left-radius: 100px;
}
.colorCodeBtn:last-child {
border-top-right-radius: 100px;
border-bottom-right-radius: 100px;
}
.colorCodeBtn {
margin: 0;
margin-top: 20px;
outline: none;
background-color: transparent;
border: 1px solid white;
font-family: "Gochi Hand", cursive;
/*color: white;*/
font-size: 24px;
}
.selectedColorCode {
background-color: white;
color: #456064;
}
.gameContainer {
font-family: "Gochi Hand", cursive;
/*color: white;*/
}
.gameQtsColor {
font-size: 60px;
line-height: 60px;
}
.gameColorsContainer {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.gameOptionsRow {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.gameColorOption {
background-color: chartreuse;
height: 150px;
width: 150px;
margin: 25px;
border-radius: 16px;
cursor: pointer;
transition: all 150ms ease-in-out;
}
.gameColorOption:hover {
transform: scale(1.15);
box-shadow: 4px 6px 24px hsla(188, 19%, 20%, 0.3);
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Colors and Numbers</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<a class="navbar-brand ms-2 mt-2 me-5" href="/">
<i class="bi bi-palette-fill"></i> &
<i class="bi bi-dice-3-fill"></i>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Game</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/generator">
Generator
</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/converter">
Converter
</a>
</li>
</ul>
</div>
</div>
</nav>
<!--* Navbar End -->
<!-- Game Body -->
<div class="colorCodeSelection">
<button class="colorCodeBtn selectedColorCode" game-mode="rgb">RGB</button>
<button class="colorCodeBtn" game-mode="hex">HEX</button>
<button class="colorCodeBtn" game-mode="hsl">HSL</button>
</div>
<div class="gameContainer container mt-5">
<p class="h3 text-center mt-5">Which Color is this?</p>
<p class="gameQtsColor text-center">rgb(20, 30, 40)</p>
<p class="text-center h3 gameMessage">Select from below!</p>
<div class="gameColorsContainer container-fluid">
<div class="gameOptionsRow">
<div class="gameColorOption"></div>
<div class="gameColorOption"></div>
<div class="gameColorOption"></div>
</div>
<div class="gameOptionsRow">
<div class="gameColorOption"></div>
<div class="gameColorOption"></div>
<div class="gameColorOption"></div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<script src="script.js"></script>
</html>Sass - Converting Hex to RGBa for background opacity
The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:
@mixin background-opacity($color, $opacity: 0.3) {
background: $color; /* The Fallback */
background: rgba($color, $opacity);
}
element {
@include background-opacity(#333, 0.5);
}If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:
$red: red($color);
$green: green($color);
$blue: blue($color);
background: rgb($red, $green, $blue); /* same as using "background: $color" */
Related Topics
Why Aren't Some Technically Serializable Input Properties Serializable
What Events Does an <Input Type="Number" /> Fire When Its Value Is Changed
JavaScript Detect Click Event Outside of Div
Detecting Flex-Wrap Support in Browsers
Bootstrap Collapsed Menu Links Not Working on Mobile Devices
How to Reset :After/:Before CSS Rules for an Element
Regex Match Count of Characters That Are Separated by Non-Matching Characters
Google Maps V3 - Limit Viewable Area and Zoom Level
How to Get Get and Post Variables with Jquery
How to Get a JavaScript Stack Trace When I Throw an Exception
Decoding Url Parameters with JavaScript
How to Save Canvas Animation as Gif or Webm
How to Disable Copy Paste (Browser)
How to Combine Jquery Animate with CSS3 Properties Without Using CSS Transitions
Change CSS Rule in Class Using Jquery
Mime Type Error with Express.Static and CSS Files
How to Ignore JavaScript Exceptions When Working with Webdriver (Htmlunit, Ruby Bindings)