Archiv für den Monat: Januar 2009

Shorten Texts via JavaScript

One day I ran into the trouble of having labes too long for the space they should go into.

In this special case I had a navigation area with a width of 150 pixel but the strings that had to go into the navigation where much longer.

So I decided that shortening the Labels by replacing the middle part by a ‘…’ would do the trick.

Here is the code for it.

fitText : function(element){
    cn=element.childNodes;     
    node=document.createElement('div');     
    node.setStyle({'float':'left',visibility:'visible','font-weight':700});
    document.body.appendChild(node);
    for(var i=0;i<cn.length;i++){
        if(cn[i].nodeType != Node.TEXT_NODE){
            continue;
        }
        origText=cn[i].data;
        text=cn[i].data.trim();
        if ( text == ''){
            continue;
        }         
        wo=element.getInnerWidth();         
	counter=0;         
	fits=true;         
	do{
            mid=Math.ceil(text.length/2);
            text1=text.substring(0,mid-counter);
            text2=text.substring(mid+counter);
            text=text1+text2;
            newText=text1+'...'+text2;
            tn=document.createTextNode(newText); 
            node.appendChild(tn);
            w=node.getInnerWidth();
            if (w>wo){ 
                fits=false;
            }
            node.removeChild(tn);
            counter++;
        } while((w>wo)&&(text.length>0))
        if ( ! fits ){
            cn[i].replaceData(0,origText.length,newText);
            element.setAttribute('title',origText);
        }
    }
    document.body.removeChild(node);
    return true; 
} 

This code requires the Prototype API.

And I believe that there are a lot of possibilities to improve that bit of JavaScript.