Coloured letters

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming. In this instance it is also appropriate for a programming class provided it is asked at the appropriate stage in the course.


Let the user type a word. Display the word in color, such that each letter's position in the alphabet determines its color. Try using a string containing the alphabet and indexOf to find the position of each input letter.

Unlike in many cases where the question specifies completely inappropriate methods to use, indexOf is actually as useful for providing the modern solution as the historical one in this case.

Historical Answer:

var colorsA = ['antiquewhite','aqua','blue','blueviolet','brown','cadetblue',
var alphabetA = 'abcdefghijklmnopqrstuvwxyz';
var str = window.prompt('Enter a word','Hello');
var output = '';
for(var i=0; i < str.length; i++) {
chr = str.charAt(i);
pos = alphabetA.indexOf(chr.toLowerCase());
output += '<span style="color:'+ ((pos != -1)? colorsA[pos] : '') + '>'+chr+'</span>';

With this example we are looking at how little modification may be needed to a historical script to have it appear reasonable as modern JavaScript. In this code the main issues are the prompt and write statements and that the HTML to be output to the page is being assembled as a text string. Since we want to process each of the characters in the string separately it also simplifies the code if we convert the string to an array first so as to not need to use charAt. Also once we have it as an array we no longer need to use a loop in the processing

JavaScript Answer:

document.getElementById('in').onblur = function() {
"use strict";
var txtNode,pos,elem,frag,str,colorsA,alphabetA;
colorsA = ['antiquewhite','aqua','blue','blueviolet','brown','cadetblue',
alphabetA = 'abcdefghijklmnopqrstuvwxyz';
frag = document.createDocumentFragment();
str = document.getElementById('in').value.split('');
str.forEach(function(chr) {
pos = alphabetA.indexOf(chr.toLowerCase());
elem = document.createElement('span'); = (pos != -1)? colorsA[pos] : '';
txtNode = document.createTextNode(chr);

With this code we are assuming that the page contains a form with an input field having id="in" into which the text can be entered. We are also assuming that there is also a div in the page with id="result" into which the generated output will be loaded. The script is presumed to be correctly attached at the bottom of the page.

As modern JavaScript this question tests the student's ability to use the basic Document Object Model commands getElementById,createElement, createTextNode, createDocumentFragment, and appendChild. A suitable followup question would be to rewrite the script so that it colours the existing content of the page instead of adding new content.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow