Search code examples
javascriptcontenteditableline-numbers

How to dynamically show line numbers in gutter according to lines in text editor box using Vanilla JS?


I need to print out accurate line numbers in the sidebar of my app using only vanilla JS.

The line numbers must auto-increase and decrease as lines are added and removed from the editable text area.

Currently it's creating new DIVs but new <code> tags would be spectacular. Unfortunately <code> tags print out on the same line instead of incrementing vertically.

My current code looks like this:

html:

<div class="textBox" contenteditable>
  <code>
    This div can be edited in browsers that support HTML5.
  </code>
  <code>
    Please edit this text and add more lines to see what needs to happen.
  </code>
</div>

JS:

  let totalLines = 1;
    function updateGutter(allLines) {
      const toAdd = document.createDocumentFragment();

  for (let i = 0; i < allLines;) {
    i += 1;
    const newDiv = document.createElement('div');
    newDiv.id = 'r' + i;
    newDiv.className = 'ansbox';
    newDiv.innerHTML = `${i}.`;
    toAdd.appendChild(newDiv);
    document.getElementsByClassName('gutter')[0].appendChild(toAdd);
  }
}

function unEqual(linesTotal) {
  if (linesTotal !== totalLines) {
    totalLines = linesTotal;
    updateGutter(totalLines);
  }
}

const getLength = function getLength(element) {
  const linesTotal = element.querySelectorAll('div').length + 1;
  unEqual(linesTotal);
};

const box = document.querySelector('.textBox');
box.addEventListener('keyup', function() {
  getLength(box);
});

But it creates an output that looks like this: enter image description here

I hope this is more explanatory. :-) * Also There's an updated FIDDLE at https://jsfiddle.net/Tranq/heyaxtd5/4/ *


Solution

  • How about using some CSS Counters magic?

    working fiddle: https://jsfiddle.net/heyaxtd5/2/

    CSS:

    pre
    {
        counter-reset: thecodenumbering;
    }
    
    code
    {
        counter-increment: thecodenumbering;
    }
    code:before
    {
        padding-right:5px;
        content: counter(thecodenumbering);
    }
    

    HTML:

    <pre>
        <code>A line of code</code>
        <code>A line of code</code>
        <code>A line of code</code>
        <code>A line of code</code>
        <code>A line of code</code>
    </pre>
    

    UPDATE:

    changed a bit your JS, it seems to be working: https://jsfiddle.net/heyaxtd5/5/