Tasty Text Trimmer

In most cases, when designing a user interface it’s best to make a decision about how data is best displayed and stick with it. Failing to make a decision ultimately leads to too many user options, which in turn can be taxing on the poor old user.

Under some circumstances, however, it’s good to give the user freedom in customising their workspace. One good example of this is the ‘Article Length’ tool in Apple’s Safari RSS reader. Sliding a slider left of right dynamically changes the length of each article shown. It’s that kind of awesomey magic stuff that’s enough to keep you from sleeping. Let’s build one.

The Setup

Let’s take a page that has lots of long text items, a bit like a news page or like Safari’s RSS items view. If we were to attach a class name to each element we wanted to resize, that would give us something to hook onto from the JavaScript.

Example 1: The basic page.

As you can see, I’ve wrapped my items in a DIV and added a class name of chunk to them. It’s these chunks that we’ll be finding with the JavaScript. Speaking of which …

Our Core Functions

There are two main tasks that need performing in our script. The first is to find the chunks we’re going to be resizing and store their original contents away somewhere safe. We’ll need this so that if we trim the text down we’ll know what it was if the user decides they want it back again. We’ll call this loadChunks.

var loadChunks = function(){
	var everything = document.getElementsByTagName('*');
	var i, l;
	chunks	= [];
	for (i=0, l=everything.length; i<l; i++){
		if (everything[i].className.indexOf(chunkClass) > -1){
			chunks.push({
				ref: everything[i],
				original: everything[i].innerHTML
			});
		}
	}
};

The variable chunks is stored outside of this function so that we can access it from our next core function, which is doTrim.

var doTrim = function(interval) {
	if (!chunks) loadChunks();
	var i, l;
	for (i=0, l=chunks.length; i<l; i++){
		var a = chunks[i].original.split(' ');
		a = a.slice(0, interval);
		chunks[i].ref.innerHTML	= a.join(' ');
	}
};

The first thing that needs to be done is to call loadChunks if the chunks variable isn’t set. This should only happen the first time doTrim is called, as from that point the chunks will be loaded.

Then all we do is loop through the chunks and trim them. The trimming itself (lines 6-8) is very simple. We split the text into an array of words (line 6), then select only a portion from the beginning of the array up until the number we want (line 7). Finally the words are glued back together (line 8).

In essense, that’s it, but it leaves us needing to know how to get the number into this function in the first place, and how that number is generated by the user. Let’s look at the latter case first.

The YUI Slider Widget

There are lots of JavaScript libraries available at the moment. A fair few of those are really good. I use the Yahoo! User Interface Library professionally, but have only recently played with their pre-build slider widget. Turns out, it’s pretty good and perfect for this task.

Once you have the library files linked in (check the docs linked above) it’s fairly straightforward to create yourself a slider.

slider = YAHOO.widget.Slider.getHorizSlider("sliderbg", "sliderthumb", 0, 100, 5); 
slider.setValue(50);
slider.subscribe("change", doTrim);

All that’s needed then is some CSS to make the slider look like a slider, and of course a few bits of HTML. We’ll see those later.

See It Working!

Rather than spell out all the nuts and bolts of implementing this fairly simple script, let’s just look at in it action and then pick on some interesting bits I’ve added.

Example 2: Try the Tasty Text Trimmer.

At the top of the JavaScript file I’ve added a small number of settings.

var chunkClass	= 'chunk';
var minValue	= 10;
var maxValue	= 100;
var multiplier	= 5;

Obvious candidates for configuration are the class name used to find the chunks, and also the some minimum and maximum values. The minValue is the fewest number of words we wish to display when the slider is all the way down. The maxValue is the length of the slider, in this case 100.

Moving the slider makes a call to our doTrim function with the current value of the slider. For a slider 100 pixels long, this is going to be in the range of 0-100. That might be okay for some things, but for longer items of text you’ll want to allow for displaying more than 100 words. I’ve accounted for this by adding in a multiplier – in my code I’m multiplying the value by 5, so a slider value of 50 shows 250 words. You’ll probably want to tailor the multiplier to the type of content you’re using.

Keeping it Accessible

This effect isn’t something we can really achieve without JavaScript, but even so we must make sure that this functionality has no adverse impact on the page when JavaScript isn’t available. This is achieved by adding the slider markup to the page from within the insertSliderHTML function.

var insertSliderHTML = function(){
	var s = '<a id="slider-less" href="#less"><img src="icon_min.gif" width="10" height="10" alt="Less text" class="first" /></a>';
	s +=' <div id="sliderbg"><div id="sliderthumb"><img src="sliderthumbimg.gif" /></div></div>';
	s +=' <a id="slider-more" href="#more"><img src="icon_max.gif" width="10" height="10" alt="More text" /></a>';
	document.getElementById('slider').innerHTML = s;
}

The other important factor to consider is that a slider can be tricky to use unless you have good eyesight and pretty well controlled motor skills. Therefore we should provide a method of changing the value by the keyboard.

I’ve done this by making the icons at either end of the slider links so they can be tabbed to. Clicking on either icon fires the appropriate JavaScript function to show more or less of the text.

In Conclusion

The upshot of all this is that without JavaScript the page just shows all the text as it normally would. With JavaScript we have a slider for trimming the text excepts that can be controlled with the mouse or with a keyboard.

If you’re like me and have just scrolled to the bottom to find the working demo, here it is again:

Try the Tasty Text Trimmer

Trimmer for Christmas? Don’t say I never give you anything!

About the author

Drew McLellan is lead developer on your favourite small CMS, Perch. He is Director and Senior Developer at UK-based web development agency edgeofmyseat.com, and formerly Group Lead at the Web Standards Project. When not publishing 24 ways, Drew keeps a personal site covering web development issues and themes, takes photos and tweets a lot.

More articles by Drew

Comments