DEV Community

Cover image for How to Generate a Random Color With Vanilla JS
Adams Stark
Adams Stark

Posted on

How to Generate a Random Color With Vanilla JS

Yesterday, we looked at how to pick a random color with vanilla JS. It required that you provide a list of colors to choose from. Today, let’s look at how to generate a random color from the entire range of valid hex colors.

Getting started #

Hex colors follow a six-digit pattern: #rrggbb, where r is the red value, g is the green value, and b is the blue value. Each character can be a letter from a to f, or a number from 0 to 9.

To get started, let’s first create a generateColor() function.

In it, will create an array with all of the valid characters for a hex color value.

var generateColor = function () {

// The available hex options
var hex = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
Enter fullscreen mode Exit fullscreen mode

Creating the hex color #

Now, let’s create the actual hex color. We’ll setup a color variable with the leading #.

var generateColor = function () {

// The available hex options
var hex = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var color = '#';
Enter fullscreen mode Exit fullscreen mode

A hex color code has six digits. We’ll setup a for loop, and run it six times.

var generateColor = function () {

// The available hex options
var hex = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var color = '#';

// Create a six-digit hex color
for (var i = 0; i < 6; i++) {
    // Do stuff...
}
Enter fullscreen mode Exit fullscreen mode

Inside the loop, we’ll use the shuffle() method we used in yesterday’s article to shuffle the array of hex characters.

Then, we’ll concatenate the first one onto the end of the color string.

When the loop is done, we’ll return the color string, which is now a random hex color code.

var generateColor = function () {

// The available hex options
var hex = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var color = '#';

// Create a six-digit hex color
for (var i = 0; i < 6; i++) {

    // Shuffle the hex values
    shuffle(hex);

    // Append first hex value to the string
    color += hex[0];

}

// Return the color string
return color;
Enter fullscreen mode Exit fullscreen mode

What is Vanilla JavaScript?

The term vanilla script is used to refer to the pure JavaScript (or we can say plain JavaScript) without any type of additional library. Sometimes people often used it as a joke"nowadays several things can also be done without using any additional JavaScript libraries".

The vanilla script is one of the lightest weight frameworks ever. It is very basic and straightforward to learn as well as to use. You can create significant and influential applications as well as websites using the vanilla script.

The team of developers that created the vanilla JavaScript is continuously working on it to improve it and make it more useful for the web-developers.

Let's have a look at some big websites that are currently using the vanilla JavaScript:

These following websites are currently using vanilla JavaScript, and these websites also mentioned on vanilla JavaScript home page.

  • Facebook

  • Google

  • YouTube

  • Yahoo

  • Wikipedia

  • Twitter

  • Amazon

  • LinkedIn

  • MSN

  • eBay

  • Microsoft

  • Tumblr

  • Apple

  • Pinterest

  • PayPal

  • Reddit

  • Netflix

  • Stack Overflow
  • It is also quite possible that most people cannot believe that the number of websites that use vanilla JavaScript is much higher than the number of websites that use JQuery.

    Why should you learn vanilla JS?

    This the very common question asked by the beginners that, when there are already so many other powerful frameworks and libraries available, why they should choose to learn vanilla Js and use it.

    There are several reasons for choosing the vanilla js to learn and use it in our projects. Here we are discussing the following three main and most important of them.

    a. Web-performance

    This is much better for web performance than many other frameworks and libraries, as it is the most expensive and important part of the front-end stack. Vanilla js code needs to be compiled and parsed, unlike HTML and CSS files, which are available to use only when they're downloaded. A file of js with a size of 50kb has a much more significant impact on web performance than the same size of HTML and CSS files.

    b. User Experience

    It provides an effortless but user-friendly developing experience.While developing an application or website using JavaScript, a developer just needs to open the text editor and can begin coding. There is no need for the developer to perform troublesome steps like npm install, compilation steps, and no build, etc.

    c. It makes working with frameworks easier as well

    In case, if any developer still wants to use any of the other frameworks, it makes working with them more comfortable as well. As we all aware of how hard it is to get started with a framework.

    There's a lot of assumed knowledge in the documentation, and understanding how all available tools works makes it quite easier to learn. A lot of beginners having little knowledge try to learn a framework, no wonders they get stuck somewhere after some time they quit focusing on the fundamentals of the Vanilla js. When they get comfortable, they again start learning frameworks, and this time they get things much quicker.

    Top comments (1)

    Collapse
     
    marcellothearcane profile image
    marcellothearcane • Edited

    Javascript already does hexadecimal calculations.

    function generateColour () {
      const randomNumber = Math.random() * 16777215 // Between 0 and FFFFFF
      const randomNumberAsInteger = Math.floor(randomNumber)
      const randomHex = randomInteger.toString(16)
      const paddedHex = randomHex.padStart(6, '0')
      return '#' + paddedHex
    }
    
    Enter fullscreen mode Exit fullscreen mode

    As one line:

    function generateColour () {
      return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
    }
    
    Enter fullscreen mode Exit fullscreen mode

    PS where is shuffle() defined?