What is the most efficient method for generating random dark colors using javascript code?

Looking for a function that specifically returns dark colors.

Although I can generate random colors with the code below, how do I make sure it only retrieves dark ones?

document.getElementById('mydiv').style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
div {
  height: 100px;
  width: 100%;
}
<div id="mydiv"></div>

If not possible, is there a way to create an array of dark colors and select from that instead?

Answer №1

Personally, I find the HSL color system (Hue, Saturation, Light) to be more user-friendly.

Here is a simple example code snippet:

const mydiv = document.getElementById('mydiv')

document.querySelector('button').onclick=_=>
  {
  let colorH = Math.floor(Math.random() *359)
    , colorS = Math.floor(Math.random() *40) +60
    , colorL = Math.floor(Math.random() *15) +7  // dark colors to adjust
    ;
  mydiv.style.setProperty('--colorBG', `hsl(${colorH}, ${colorS}%, ${colorL}%)`)
  }
#mydiv {
  --colorBG: hsl(0, 100%, 15%);  /* 0..359 */
  display: block;
  height: 100px;
  width:100px;
  background-color: var(--colorBG);
  }
* {margin: 1em;}
<div id="mydiv"> </div>

<button>Random color</button>

Answer №2

The depth of darkness increases with lower levels, reaching full range at 256.

lvl = 128;
color = Math.floor(Math.random()*lvl)<<16 | Math.floor(Math.random()*lvl)<<8 | Math.floor(Math.random()*lvl);
document.getElementById('mydiv').style.backgroundColor = '#' + color.toString(16).padStart(6, "0");
div { height: 100px; width:100%; }
<div id="mydiv"/>

Answer №3

When it comes to colors, they are essentially mixtures of red, green, and blue with values ranging from 0-255 for each. The darkest version of a color is represented by 0 (which is basically black), and the lightest is represented by 255 (white).

If you're aiming for a "dark" color, stick to the lower half of the 0-255 range and choose values between 0 and 127. To convert these values into hex colors, simply use .toString(16). Repeat this process three times - once for R, once for G, and once for B.

To ensure that each base 16 value between 0-127 has a leading 0 when necessary, just add a "0" at the beginning and then use slice to extract the last two characters, omitting the unnecessary "0".

Selecting colors randomly doesn't require much explanation.

document.getElementById("dark").style.background = "#" + ("0" + rando(127).toString(16)).slice(-2) + ("0" + rando(127).toString(16)).slice(-2) + ("0" + rando(127).toString(16)).slice(-2);
document.getElementById("darkFromPool").style.background = rando(["black", "darkgreen", "darkred"]).value;
div { height: 50px; margin: 10px 0px 30px 0px; border-radius: 4px; }
<script src="https://randojs.com/1.0.0.js"></script>

Random dark: <div id="dark"></div>
Random dark from pool: <div id="darkFromPool"></div>

This code simplifies randomness using randojs.com to enhance readability. If you intend to utilize this code, ensure that the following script tag is included in the head section of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>

Answer №4

Discover how to create random color combinations using HTML, CSS, and Javascript with the code snippet below:

const setBg = () => {
  const randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#" + randomColor;
  color.textContent = "#" + randomColor;
}

genNew.addEventListener("click", setBg);
setBg();
body {
  height: 100vh;
  margin: 0;
  padding: 1rem;
  display: grid;
  place-items: center;
  font-family: system-ui;
}
h1 {
  background: white;
  padding: 1rem 2rem;
  text-align: center;
}
span {
  display: block;
  padding: 1rem;
  font-size: 1rem;
  font-weight: normal;
  font-family: monospace;
  text-transform: uppercase;
}
<h1>
  <button id="genNew">Generate New Random Color</button>
  <span id="color"></span>
</h1>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

Alter the navigation background when moving between sections on a one-page website

I need to ensure that the background of the navigation remains transparent on the "home" section. However, when switching to other sections, the background color of the navigation becomes permanently black. <header class="clearfix"> <nav> ...

Is it possible to use Next Image to load multiple images within a loop effortlessly?

I have the following array of template types: const TEMPLATE_TYPES = [ { name: 'Blog Post', type: 'blog-post', img: '/img1.png' },... ]; In a later stage, I'm iterating over TEMPLATE_TYPE ...

Converting a List of Maps from Immutable.js into a List of Lists and utilizing it as the dataset for Google Charts

I am currently working on implementing the Google Charts library to visualize some time series data. Right now, I have dummy data stored in a separate file from my application. In this file, I have an Immutable List structured like this: le ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

How to create select options in Angular.js without using the ng-option directive

I receive a JSON object from a service and I am using some of its fields to populate my select option list. However, when I try to print the selected value in my controller, the output response is "undefined". Can someone help me figure out what I'm ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

What steps can I take to troubleshoot a non-functional button in a Bootstrap 5 Modal?

I have a Django based web site that utilizes Bootstrap 5 for styling. Among the data presented on the site is a table with a notes column containing lengthy text. To enhance readability and keep the table compact, I attempted to integrate the Bootstrap Mod ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Transforming the API response

After making an Ajax call, the response received is: console.log(data); {"valid":true,"when":"Today"} Attempting to read the response like this: var res = data.valid; console.log(res); results in 'undefined' being displayed. To address this i ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

Obtaining and storing multiple checkbox selections in a database using a JSP page

If users are required to input data on the first page, such as City, Country, and URL of the destination, and they need to select the type of destination from options like Winter, Christmas, and Summer (max 2 selections), how can these results be connected ...

Retrieving the correct selected value from multiple select tables created through a for loop can be achieved using JavaScript or jQuery

Despite searching Google and asking previous questions, I have not found a solution that addresses my specific issue. The common responses only pertain to one select element with multiple options. To further clarify, when I create code for a loop to genera ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

Neglecting to automatically align text

My goal is to automatically align text based on the language, so that Arabic text starts from the right and English text starts from the left. After some online research, I discovered that I need to use dir="auto" in the tag and text-align: auto; in the CS ...