Add Numbering to Pre and Textarea – line-numbers Web Component

Category: Javascript | June 9, 2025
Authorzachleat
Last UpdateJune 9, 2025
LicenseMIT
Views81 views
Add Numbering to Pre and Textarea – line-numbers Web Component

<line-numbers> is a lightweight web component that adds line numbers to <pre> and <textarea> elements. It even dynamically updates with <textarea> input.

Features:

  • Non-Selectable Numbers: The numbers are rendered in the Shadow DOM.
  • Multi-element support: Works with both <pre> and <textarea> elements
  • Real-time updates: Line numbers automatically adjust when adding or removing lines in textareas
  • Overflow handling: Supports CSS overflow with both obtrusive and non-obtrusive scrollbar behavior
  • Copy-paste friendly: Line numbers are excluded from text selection and content flow
  • Customizable numbering: Supports any CSS counter style via --uln-number-type custom property
  • Flexible starting index: Set custom starting numbers with the start attribute
  • Layout-aware: Non-obtrusive by default to prevent layout shift, with opt-in obtrusive mode

How To Use It:

1. Install <line-numbers> and import it into your document.

# NPM
$ npm install @zachleat/line-numbers
<script type="module" src="./line-numbers.js"></script>

2. Wrap your target element with <line-numbers>:

<!-- Pre -->
<line-numbers>
  <pre>
    const greet = () => {
      console.log("Hello, world!");
    };
  </pre>
</line-numbers>
<!-- Textarea -->
<line-numbers>
  <textarea>
    Initial text in the area.
    Add more lines here.
  </textarea>
</line-numbers>

3. Custom starting index:

<line-numbers start="10">
  <pre>// Code starts at line 10</pre>
</line-numbers>

4. Obtrusive mode (line numbers take up layout space):

<line-numbers start="10">
  <pre>// Code starts at line 10</pre>
</line-numbers>

5. Disable the automatic input event listener on a <textarea>. You would then need to call the render() method on the element yourself to update the line numbers.

<line-numbers manual-render>
  <pre>// Code starts at line 10</pre>
</line-numbers>
document.querySelector('line-numbers').render();

6. Available CSS variables to customize the line numbers:

  • --uln-number-type: Change counter style (decimal, roman, etc.)
  • --uln-color: Line number text color
  • --uln-font: Line number font properties
  • --uln-padding-h: Horizontal padding for line numbers
  • --uln-padding-v: Vertical padding for line numbers

You Might Be Interested In:


Leave a Reply