Text excerpts via CSS, javascript and the DOM

Posted on October 27, 2005

Excerpts (or teaser boxes) from longer texts can help the user when scanning and serve to highlight key points or quotes. Here's an example of automatically generated excerpts using CSS, javascript and the DOM. It degrades gracefully.

When the makeExcerpts function is called, it first checks if stylesheets are activated by attempting to read the style attributes of the css_sniffer div.

// is stylesheet activated?
sniffer = document.getElementById("css_sniffer");

if (sniffer.currentStyle) // IE
	css = sniffer.currentStyle['left'];
else if (window.getComputedStyle) // Mozilla / Opera
	css = document.defaultView.getComputedStyle(sniffer,null). ¬
	getPropertyValue('left');
else
	css = "0px";
	
if (css == "auto") // css not activated
	return false;

(I'm giving non-IE, non-mozilla browsers the benefit of the doubt)

If css is activated, the script loops through all em nodes with the class attribute "excerpt". The content of each em is copied, and is inserted in a new node, created as the first child of the em's parent.

eleArr = document.getElementsByTagName("em");

for (i=0;i<eleArr.length;i++) {
	if (eleArr[i].className == "excerpt") {
		newNode = document.createElement("span");
		newNode.className = "excerptbox";
		newNodeTxt = document. ¬
		createTextNode( eleArr[i].firstChild.nodeValue );
		newNode.appendChild( newNodeTxt );
		
		parNode = eleArr[i].parentNode;
		parNode.insertBefore(newNode, parNode.firstChild);
	}
}

The new spans are styled with the class "excerptbox", which in the example floats them in a box to the right of the paragraph. If javascript is active on the client machine, but stylesheets are deactivated, the text appears to be inserted out of context at the beginning of the paragraph. That's why it is important to check if css is available.

The major benefit of this approach is in text maintenance; we eliminate the redundancy of having the same text appear twice in the document.



Comments (1)

Nik said

Working on a project right now which could use these snippets very well... nice work! :)

Posted by: Nik at December 29, 2005 09:15 AM .