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

Add Numbering to Pre and Textarea – line-numbers Web Component
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

The post Add Numbering to Pre and Textarea – line-numbers Web Component appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading