Tech » JS

frameworkhelpersOOlogginglocal stringsmulti class names


I am using a simple editor and Firefox with the following extensions: 'DOM Inspector', 'Web Developer', 'FireBug' and 'InspectThis'.
Also Subversion and TortoiseSVN helped a lot.

Here are some random programming patterns, that I found useful.

Little helpers

Some of the helper functions I am using (have a look at the protoype.js library for much more):

function $(e) {
	return (typeof e == 'string') ? document.getElementById(e) : e;

function toggleVisible (e) {
	var b = $(e).style.display != 'none';
	$(e).style.display = b ? 'none' : '';
	return b;
var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }

Object orientated JavaScript

JavaScript is an often underestimated language, that offers a lot more than mouse-hover-gif-switching. Especially the ability to do object-orientated programming makes it a serious and powerful language.
I was also pretty impressed about the performance: the tree view implementation deals with thousands of nodes, and the sudoku game solver is fast enough to solve a puzzle within the Firefox time limit (mostly).

I am not going to explain OO-JS here; there are a lot of ressources on the net, for example OOP in JS or Object-Oriented Programming with JavaScript.
Here is a simple example to define a class named CLazyTreeNode:

var CLazyTreeNode = Class.create();
CLazyTreeNode.prototype = { initialize: function(tree, data) { this.tree = tree; if ( typeof data == 'string' ) { this.title = data; } else { this.title = data.title; } this.parent = null; // not yet added to a parent this.bIsFolder = false; }, inspect: function() { return '"' + this.title + '" (' + + ')'; }, [...]


var pos = new CYasonPos (this);


This pattern allows to write debug messages to the browser window.

The html page must contain an empty div-tag where the output should appear:
<div id='idLogPanel'> </div>.

When the debugging is disabled, or the output panel is not defined, a call to logMsg() will return immediately, so there is only a small impact in release mode.
A time tag is prepended, so it can be used for timings as well. Note however that printing debug messages takes some time itself, especially if there are a lot of lines.

Here is the code:

var bDebug = true;
var divLogPanel = null;
function logMsg (msg) {
	if ( !bDebug  )
	if ( !divLogPanel ) {
		divLogPanel = document.getElementById('idLogPanel');
		if ( !divLogPanel ) {
			bDebug = false;
	var dt = new Date();
	divLogPanel .innerHTML += dt.getHours()+':'+dt.getMinutes()
     + ':'+dt.getSeconds()+'.'+dt.getMilliseconds()
	   + '  ' + msg + '<br>';

Usage (see here for a demo):

// append a log message:
logMsg ('expand ('+this.title+')...');

Local strings

This pattern allows to define multi-language strings and display them in the users preferred language (see here for a demo).

function localString (msg) {
	/* language is FF only (refers to browser settings?)
	 * systemLanguage/userLanguage is IE only (refers OS lnaguage?)
	if ( typeof msg == 'string' )
		return msg;
	var lang = navigator.userLanguage ? navigator.userLanguage : navigator.language;
	lang = lang.toLowerCase();
	if ( lang.indexOf('-')>0 )
		lang = lang.substring (0, lang.indexOf('-'));
	if ( typeof msg[lang] == 'string' )
		return msg[lang];
	if ( typeof msg['en'] == 'string' )
		return msg['en'];
	return '<no local string found for language '+lang+'>';


var CS_Solved = { en:'The Sudoku is solved.', de:'Das Sudoku wurde gelöst.' };
alert (localString(CS_Solved));

Multiple class names

Assigning multiple class names to an html element is a standard CSS feature, but seems to be rarely used.
An example could be a number of <input> elements, that have a common class name to apply some CSS style:
<input class='boardCell'>.
The input element that has the input focus should be marked with a red border. This can be done by a second additional class name separated by a blank like this: <input class='boardCell focus'>.

To achieve this, we call addClassName() in the onfocus-event, and remove it onblur (see here for a demo):

<input type='text' class='boardCell' 
    onblur='removeClassName(this,"focus")' >

Here are the tool functions:

function addClassName (o, className) {
    var a = o.className.split();
    for (var i=0; <a.length;i++)
        if ( a[i]==className )
    o.className += ' ' + className;
function removeClassName (o, className) {
    o.className = o.className.replace (className, '');

And this could be the stylesheet:

	border-style: inset;
	border-color: red;



© martin wendt