Limit the random color generator function to only produce a predetermined color in JavaScript

By utilizing the following function, I am able to create random colors:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

However, I have a requirement to exclude "#A9A9A9" or any shades of grey from the generated colors. Simply adding an if condition after generating the color and calling the function again does not appear to be an efficient solution. Can you provide suggestions on how this can be achieved?

Answer №1

In order to eliminate true grey from your color palette, you can make some adjustments to your code. One option is to use the HSL color space:

var color = 'hsl(' + Math.round(Math.random() * 359) + ',100%,50%)';

By setting specific ranges for Hue and ensuring Saturation/Lightness are at reasonable levels, you can avoid generating grey, black, or white colors. For those who prefer RGB, it's possible to convert HSL to RGB using libraries like https://github.com/Qix-/color-convert.

To demonstrate a more advanced approach, here is a function that generates non-green colors based on defined hue ranges:

randomNonGreenColor = function () {
    //skip green
    var ranges = [[0, 60], [180, 359]];

    var total = 0, i;
    for (i = 0; i < ranges.length; i += 1) {
        total += ranges[i][1]-ranges[i][0] + 1;
    }

    var randomHue = Math.floor(Math.random() * total);

    var pos = 0;
    for (i = 0; i < ranges.length; i += 1) {
        pos = ranges[i][0];
        if (randomHue + pos <= ranges[i][1]) {
            randomHue += pos;
            break;
        } else {
            randomHue -= (ranges[i][1] - ranges[i][0] + 1);
        }
    }

    return 'hsl(' + randomHue + ',100%,50%)';
}

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

Choosing just the element that was clicked and added to the DOM

I've been experimenting with JQuery in a web app I'm developing. The app involves dynamically adding elements to the DOM, but I've encountered an issue with click events for these newly added elements. I'm looking for a way to target an ...

Using Javascript REGEX, transform an array into a string where each element is enclosed in curly braces

Currently in my Javascript project, I am faced with the challenge of converting an array into a string with curly braces around each word. The input array is: ["apple", "brand", "title"] Desired output: '{apple} {brand} ...

Persistently Undefined Angular Attribute

I have been trying to dynamically bind a CSS class using an AngularJS function. While the functionality is working properly, I keep encountering numerous errors in the browser console. Can anyone offer assistance with this issue? I have included my code an ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Uploading files with node.js and express

Currently, I am following the steps outlined in this tutorial: I have successfully followed the instructions until the section where they set up the routes without actually creating any views. The tutorial states: That's it, we have completed sett ...

AngularJS is unable to properly display (parse) data fetched using $http.get from Laravel5

Working on my SPA project, I have integrated Laravel 5 for database management and used AngularJS for the front-end. All Angular files are stored in the public folder. Instead of displaying a list of users when visiting localhost, it shows: {{ user1.name ...

What is the process for connecting a Wii Remote with Three.js?

Suppose I wanted to explore Wii Remote to browser interaction by connecting it to my Ubuntu laptop via Wiican and Wmgui using Bluetooth. What would be a simple program to achieve this? I have successfully used an Xbox Gamepad with Chrome, so I know that i ...

What is the procedure for populating a listbox with items selected from an array?

On my aspx page, there is a listbox (techGroups) with preselected items that users can change. I also have a reset button that should restore the listbox to its original selections when clicked. However, I am encountering an issue where only the first pres ...

"Oops! Looks like there is an issue with the configuration of the builder. Try running `npm run storybook

Encountering an error when attempting to execute npm run storybook following what seems like a smooth installation of Alpha 7. Any suggestions on where to begin troubleshooting this issue? https://i.sstatic.net/EEFx4.png ...

Attempting to output properties from an Express/Mongo API by utilizing a React.js frontend

I am currently in the process of developing a simplistic fictional sneaker application with the MERN stack. While I wouldn't classify myself as a beginner, I'm also not an expert. I successfully created the backend and generated a json rest-api. ...

Merging two-dimensional arrays conditionally

I am working with 2 Arrays, arr1 = [ ['itemid-1', 'itemclass', 'timestamp'], ['itemid-2', 'itemclass', 'timestamp'], ['itemid-3', 'itemclass', 'timestamp&apos ...

Having difficulty fetching data from a RESTful API to generate a JSON object using Node.js

I have developed a RESTful API to retrieve data from an external API located at . The data retrieval is successful. However, I am looking to implement a feature where if a query like "/api/rates?currency=EUR,GBP,USD" is made, the following rates ...

Implementing React selectors to manage the state changes on page load and when a user

I'm currently delving into React selectors with ReSelect, and while things seem to be going well, I have a feeling that there may be an issue in my logic. 1 - Upon receiving an AJAX response, I obtain a list of "categories" consisting of id, name, an ...

Having issues with ToggleClass and RemoveClass functionalities not functioning properly

As a novice in Jquery and CSS/scss, I've managed to create dynamic bootstrap cards for recording players. Each card consists of a music-container with control-play and vinyl elements. I aim to have multiple bootstrap cards generated based on the data ...

Clearing cookies in Express.js can be a challenging task

I've tried multiple options, but I can't seem to delete the cookie. Can anyone help me understand this? I have attempted using set maxage, expires, setheaders, but nothing seems to delete the cookie. It's impossible. res.cookie("refres ...

Modify the appearance of certain text within an input field

I need some help adding style to specific text within an input field. For example, if the user types in "Hello world" and the special text is "world" I want to achieve this result: https://i.sstatic.net/Ozd6n.png This is what my HTML code looks like: & ...

Notifying when a refreshed PHP interactive clock has detected new input

I have created a simple countdown timer in PHP that will continuously update the result to be displayed on the page using JavaScript. I am still deciding whether updating every second could potentially cause any issues. The way the countdown works is by r ...

Tips for importing a Multimaterial .dae file in three.js?

I am facing an issue while trying to load a model with multiple materials. I want to access the array of materials but my current approach is not working as expected. loader.load('./dae/tenis.DAE', function ( collada){ dae = collada.scene; ...

"Previewing multiple images before uploading for a better visual experience

I am working on a project to enable previewing multiple images, but I encountered an issue. My current code only works when uploading 2 images. I want the preview to work for as many images as the user uploads. Here is the relevant JavaScript code: var a ...

What is the best way to showcase an ajax response on an HTML webpage?

Apologies for the length of the code, but I'm looking to condense it while maintaining the same functionality. Is there an alternative approach or method that could achieve the same results? I receive data from PHP, which is then passed to JavaScript ...