How to Manipulate Colors in JavaScript Using Chroma.js

In today’s tutorial screencast I’m going to show you how to manipulate colors with JavaScript. That’s right, JavaScript. Not CSS. Let’s dive in to see what I’m talking about!

Watch Screencast

We’ve all become used to the idea that CSS handles styles whilst JavaScript is used for behavior, and the two concerns should be kept separate. But when it’s not possible to define styles directly via CSS, such as when they’re set via user input, JavaScript will do all the heavy lifting for you.

Chroma.js is a small library which can be a big help with manipulating colors, so let’s see how to get started using it.

Hook it Up

Chroma can be pulled from its repo on Github, or linked to from CDNJS using this link:

This is a big chunk, but is much less intimidating than you may at first think! It begins with an event listener DOMContentLoaded which waits until the document is loaded before executing any of the function which follows.

Next I define a bunch of variables which we’re going to use, starting with two buttons, then the colorScheme and colorScale containers, then steps (a number we’ll use shortly).

Lastly, there are two click event listeners with (as yet) empty functions.We’re going to begin with the first of these, the btnGenerateColorScheme, which is (unsurprisingly) the button which will generate a color scheme.

btnGenerateColorScheme

Within the empty function, between the curly braces, we’ll start by setting an empty array called colorList:

// Reinitialize the color list.
colorList = [];

When a user clicks the button the first thing we need to do is get the color from the #user-color input.

Then we need to reset the values within the color scheme list. This is done by stripping the innerHTML of the .color-scheme element, which is in our case an <ol>. Here you can see we’re making the innerHTML equal an empty string.

Done!

We’ve successfully built a color scheme generator which outputs a series of blocks, starting with the picked color and gradually getting darker.

Our color scheme

You might want to improve this by having the picked color placed in the middle of the range with lighter colors to the left and darker colors to the right, in which case take a look at the video and follow along with the final steps. You could also add color details for each block, such as the hex value; I also explain this in the screencast.

Lastly, the screencast also includes instructions for building the color scale generator, so jump in and let me know how you get on!