Adding Line Numbers To HTML Textarea

I have a <textarea /> as in the code below. How do I display the line numbers on the left hand side of it?

Is there a jQuery plugin?

<TEXTAREA name="program" id="program" rows="15" cols="65" ></TEXTAREA>

Solution 1:

There is Lined TextArea (Link no longer valid, see mirror) plugin for jQuery by Alan Williamson
MIT License
jQuery 1.3+

Solution 2:

You can very well try Code Mirror, which is a JavaScript library for embedding a code editor in a web page.

With code lines, it has great features like

  • Autocompletion
  • Themes
  • Mixed language modes
  • Search
  • Merge/diff interface
  • Custom scrollbars etc.

Solution 3:

This is a very simple, but effective trick. It inserts an image with the line numbers already added.

The only catch is you may need to create your own image to match your UI design.

https://jsfiddle.net/vaakash/5TF5h/

textarea {
    background: url(http://i.imgur.com/2cOaJ.png);
    background-attachment: local;
    background-repeat: no-repeat;
    padding-left: 35px;
    padding-top: 10px;
    border-color:#ccc;
}

Credit goes to: Aakash Chakravarthy

Solution 4:

No one tried to do this using HTML5 Canvas object and by painting line numbers on it. So here what I've managed to pool in few hours. Put canvas and textarea, one next to the other, and painted numbers on canvas.

https://www.w3schools.com/code/tryit.asp?filename=G68VMFWS12UH

enter image description here

true there is limitation we can't handle word-wrap easy in Paint() function without iterating entire textarea content and offdrawing to mirror object for measurements of each line height. Also would yield very complex code.

preview image