First off here’s a little demo of a styled list:
See the Pen JS Gradient by Phil Maurer (@aurer) on CodePen.
You can find the script at github.com/aurer/jsgradient if you want to try it out.
This project originally grew from the the question of how to replicate the most basic part from the popular and awesome app Clear, that being the graduated color list denoting importance of tasks. The problem is automating the process of coloring a series of items using a gradient of colours from X to Y given that the list can be of any length.
Converting hexadecimal colors to RGB
In order to find the colours between two colours, you need to take the hexadecimal representation of the colour e.g. #07E3F2 and convert it to an RGB version (in this case R=7, G=227, B=242).
It turns out it’s quite simple to do, the hex string contains 6 characters, the first two represent Red, the next two Green and the last two Blue and each one is in base 16 i.e. 0,1,2,4,5,6,7,8,9,A,B,C,D,E,F. The following javascript can convert each colour from base 16 to it’s base 10 equivalent.
var R = parseInt(hex.substr(0, 2), 16);
var G = parseInt(hex.substr(2, 2), 16);
var B = parseInt(hex.substr(4, 2), 16);
Do that for the start and end colours, then using those numbers you can work out the ones in between.
To work out the numbers in the middle, take difference between the start and end numbers and divide by the number of steps you want. Using the result as an increment, simply remove or add it to the start number until you reached the end number, recording each one along the way and converting back into hex.
So maybe there’s a better way to do it, but this does work ok it seems.
The jsgradient plugin
The easiest way to implement a gradient is by calling the gradientList() function, specifying the start color, end color and list element you want to style like so:
jsgradient.gradientList('#07E3F2', '#155994', '#demo');
You can pass in the colors in the following formats: ‘fff’, ‘#fff’, ‘ffffff’ or ‘#ffffff’. The list element can also be passed in as a string e.g. ‘#demo’ or as a jquery object e.g. $(‘#demo’);
You can also call the generateGradient() function as the example below shows and this will return the array of hex colors for you do use however you like.
jsgradient.generateGradient('#07E3F2', '#155994', 10);