Home & blog  /  2012  /  Jan  /  view post  /

Numberfy: add line numbers to your textareas

posted: 23 Jan '12 18:31 tags: line numbers, textarea, jQuery

Ever wished textareas had native support for line numbers?

I, and doubtless the developers behind the many JSFiddle-esq sites out there these days, have.

So I've built a jQuery plugin that does precisely that. Just target the textarea(s) you want to add line number support to via a jQuery selector, call the numberfy method, and that's it.

Head over here to download, get usage info or view a demo.

$('#myTextarea').numberfy();

This tuned out to be an interesting little thing to build. The most challenging part, obviously, was getting the numbers to appear at the right positions vertically, to take into account line wrapping.

The solution here is simple but effective; on every keypress in the textarea, the textarea's current value is split into lines, then one by one each line is added to the clone and its offset height measured.

That tells us how tall the line is, including wrapping, and tells us therefore where to position the line number.

It's worth pointing out that the clone is not actually a clone of the textarea - it's a<p> tag; the reason is the clone needs to have fluid height, so we can read its offset height. A textarea's dimensions are never fluid.

IE, sod off

It doesn't currently work correctly in IE. This is because I discovered a little-known 'bug' in IE whereby text within textareas wraps differently from text in other areas - even where they have the same word-wrap / white-space CSS properties.

I moaned about it on Stack Overflow, and the consensus so far seems to be there's nothing that can be done about it. I'll keep looking at this.

Head over here to download, get usage info or view a demo.

Enjoy.

post new comment

Comments (0)