jump to content

Extract a web site’s colour palette

Hextractor is an awesome tool. From their website:

Hextractor will extract the colors from your stylesheet — whether they're hex codes, RGB, or named colors — and generate a color palette from them showing you exactly what you've got, displayed in the formats you prefer.

However, extracting the colours does rely on a server-side php script and I thought it would make an ideal javascript bookmarklet. An example of the result is shown on the right.

This page also helps me to documents some common javascript examples and links for reference.

How to install the colour palette bookmarklet

Try it now! Click this link to view the colours on this site.

To use on other web sites, click and drag this show page colours link to add it to your favorites or bookmarks bar. Visit the web site you would like to see the colour palette of and click on the bookmark or favorite. It will then show the 'Colours used on this page' table.

  1. What is a bookmarklet?
  2. Outline of the colour palette bookmarklet
  3. Code deconstruction
  4. Using JSLint for best practice javascript
  5. Compressing the bookmarklet

What is a bookmarklet?

bookmarklet, or favelet is usually a small piece of javascript that can modify a page in a particular way. By adding the bookmarklet to a user's bookmarks, it can be executed on any web page. Examples of bookmarklets include:

Outline of the colour palette bookmarklet

The bookmarklet can be broken down into the following steps:

  1. Get all the html tags that make up the web page
  2. Examine each tag to see its text colour, border colour and background colour.
  3. Add each colour to a holding array
  4. Show a list of distinct colours and their values

Code deconstruction

Full listing with line numbers:

1  'use strict';
2  /*global window: false */
3
4  (function () {
5    var elements = document.getElementsByTagName('*'),
6    elementsLength = elements.length,
7    attributes = ['color', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor', 'backgroundColor'],
8    colours = {},
9    style,
10   output = '',
11   count,
12   property;
13
14   do {
15     style = elements[elementsLength - 1].currentStyle ? elements[elementsLength - 1].currentStyle : window.getComputedStyle(elements[elementsLength - 1], null);
16     for (count = 0; count < attributes.length; count += 1) {
17       colours[style[attributes[count]]] = colours[style[attributes[count]]] === undefined ? 1 : colours[style[attributes[count]]] + 1;
18     }
19   } while (--elementsLength);
20
21   for (property in colours) {
22     if (colours.hasOwnProperty(property)) {
23       output += '<li style=%22margin:3px;padding-left:3px;border-left:solid 50px ' + property + '%22>' + property + ' (' + colours[property] + ')</li>';
24     }
25   }
26
27   document.getElementsByTagName('body')[0].innerHTML = '<ol style=%22color:#111;margin:5px;padding:5px;width:250px;border:solid 1px goldenrod;background:#fff;opacity:0.9;%22><li style=%22padding:0 0 5px 0;font-weight:bold;color:#111;%22>Colours used on this page</li>' + output + '<br><a href=%22http://www.bassett-jones.com/page-colours-bookmarklet%22>About this bookmarklet</a> | <a href=%22http://hugh.bassett-jones.com%22>By Hugh</a></ol>' + document.getElementsByTagName('body')[0].innerHTML;
28
29 }());

Line 1 is a way of reporting errors when using poor javascript practice. John Resig covers it in more detail in ECMAScript 5 Strict Mode.

Line 2 comment used for the JSLint checker.

Line 4 encapsulates the javascript to avoid conflicts and global scope of variables. Stack Overflow has a great explanation.

Lines 5-12 declare and initial all variables used in the script.

Lines 14 + 19 efficiently loop backwards through all the elements in the page.

Line 15 get the computedStyle for non-IE browsers or the currentStyle for Internet Explorer.

Line 16 loop through the list of previously declared style attributes such as background colour and border colour.

Line 17 check whether the holding colour list already contains the style colour. If so, add to the count, otherwise add it to the list.

Line 21 loop through the properties of the colour holding list.

Line 22 hasOwnProperty removes properties inherited through the prototype chain.

Line 23 adds a html list item to the output string. %22 is the escaped value of ", as the raw quote symbol will eventually be used in the href link.

Line 27 inserts the output string at the top of the <body> tag.

Using JSLint for best practice javascript

Once the javascript is written and tested in a couple of browsers to make sure it works, it can be a good idea to run it though JSLint to test for code quality. The colour palette bookmarklet was run through with 'The Good Parts' and 'Assume a browser' checked, which results in the options list of:

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true */

Compressing the bookmarklet

Internet Explorer supports a maximum URL length of 1,083, with other modern browsers having no effective limit. This means that the javascript needs to be under 1,083 characters in total to work in IE. Luckily, there are a number of javascript compressors available online which can crunch variable names to single characters, remove unnecessary comments and delete white space.

Using the YUI compressor results in 1,010 characters for the colour bookmarklet

javascript:'use strict';(function(){var g=document.getElementsByTagName('*'),c=g.length,b=['color','borderTopColor','borderRightColor','borderBottomColor','borderLeftColor','backgroundColor'],h={},d,a='',e,f;do{d=g[c-1].currentStyle?g[c-1].currentStyle:window.getComputedStyle(g[c-1],null);for(e=0;e<b.length;e+=1){h[d[b[e]]]=h[d[b[e]]]===undefined?1:h[d[b[e]]]+1}}while(--c);for(f in h){if(h.hasOwnProperty(f)){a+='<li style=%22margin:3px;padding-left:3px;border-left:solid 50px '+f+'%22>'+f+' ('+h[f]+')</li>'}}document.getElementsByTagName('body')[0].innerHTML='<ol style=%22color:#111;margin:5px;padding:5px;width:250px;border:solid 1px goldenrod;background:#fff;opacity:0.9;%22><li style=%22padding:0 0 5px 0;font-weight:bold;color:#111;%22>Colours used on this page</li>'+a+'<br><a href=%22http://www.bassett-jones.com/extract-a-web-sites-colour-palette%22>About this bookmarklet</a> | <a href=%22http://hugh.bassett-jones.com%22>By Hugh</a></ol>'+document.getElementsByTagName('body')[0].innerHTML}());

Leave a reply