I want to have a textarea which displays line numbers on the left. Wrap should be set to "off" (so that horizontal scrolling is available). I want to have my page as a single self-contained .html file (there will be no graphics), so I'd like to avoid any 3rd party frameworks.
Which way should I go? How would you do this?
Without images, that's a tough one.
Best bet: Place a second textarea with identical settings (font size, line height, padding...) but different styling (no background color, no borders) to the left of your original textarea. Make it read only, take it out of the tab rotation (
tabindex=99999
might do the trick or simply disabling it), and put line numbers in it. This should work well and correctly as far as I can think, it should even survive things like the client resizing the font manually in their browser.You could even use
position: relative
and a bigpadding-left:
value in the original textarea to move the counter textarea into the original one.Downside: The line counter won't follow vertical scrolling of the textarea. See the comments below.
Another simple method is to create a narrow, but tall background image and some left padding on the textarea. This has the minor caveat of having a fixed number of rows and font style, but it is the option with the least amount of code required.
You'd have to wrap the text area and capture the keystrokes looking for newline characters (Eg ENTER). Doing a quick Google search and you get http://www.dhtmlgoodies.com/forum/viewtopic.php?t=506
I think your best bet would be to just have a regular textarea, and show a preview (like stack overflow) as they type along. Within that preview, you could easily add line numbers on each line and format the look via CSS.
I would start with two text-areas and synchronzation mechanism. Something like this,
Ofcourse
populate()
function (and the style declaration and event declaration) should be more robust and intelligent, , but, it just for showcase purpose.Personally I'd just have a regular textarea and a div down the left side that displays the numbers (possibly auto-adjusting as more carriage returns get added to it).