Search code examples
javascripthtmlwebcode-editor

How to implement custom code editor with HTML/JavaScript?


hello I'm trying to create syntax highlight in my web texteditor and my function is working and not at the same time I don't know why

when I type the word:

but in the editor:

this is the code:

const textarea = document.getElementById('editor');

updateText(textarea.value);

textarea.addEventListener("keydown", function(e) {
  setTimeout(() =>{
    updateText(textarea.value);
  },0)
})


function updateText(text)
{
  textarea.innerHTML = colorize(text.replace(/\n/g, "<br>").replace(/\t/g,"&#9;"));
}


function colorize(text)
{
var words = ["int","class","#include","namespace"];
  for(const keyword of words)
  {
    text = text.replaceAll(keyword,`<span style="color:#569cd6">${keyword}</span>`)
    text = text.replaceAll(keyword.toLowerCase(),`<span style="color:#569cd6">${keyword.toLowerCase()}</span>`)
  }
  return text
}

I tried to make it change color


Solution

  • So here's what I have tried following your approach, it still needs improvement, thou:

    const textarea = document.getElementById("editor");
    
    function moveCursorAtTheEnd() {
      var selection = document.getSelection();
      var range = document.createRange();
      var contenteditable = document.querySelector('div[contenteditable="true"]');
      if (contenteditable.lastChild.nodeType == 3) {
        range.setStart(contenteditable.lastChild, contenteditable.lastChild.length);
      } else {
        range.setStart(contenteditable, contenteditable.childNodes.length);
      }
      selection.removeAllRanges();
      selection.addRange(range);
    }
    
    textarea.addEventListener("keydown", function (e) {
      if (e.keyCode == 32 || e.keyCode == 13) updateText(textarea.textContent);
      textarea.innerHTML = textarea.innerHTML + " ";
      moveCursorAtTheEnd();
    });
    
    function updateText(text) {
      textarea.innerHTML = colorize(
        text.replace(/\n/g, "<br>").replace(/\t/g, "&#9;")
      );
    }
    
    function colorize(text) {
      var words = ["int", "class", "#include", "namespace"];
      for (const keyword of words) {
        text = text.replaceAll(
          keyword,
          `<span style="color:#569cd6">${keyword}</span>`
        );
        text = text.replaceAll(
          keyword.toLowerCase(),
          `<span style="color:#569cd6">${keyword.toLowerCase()}</span>`
        );
      }
      return text;
    }
    #editor {
      background: lightgrey;
      height: 100vh;
    }
    [contenteditable]:focus {
      outline: 0px solid transparent;
    }
    <div contentEditable="true" id="editor" onfocus="this.value = this.value;"></div>

    After all, for a robust editor, I'd recommend you to use ACE editor, you can have a look at the live demo here: https://ace.c9.io/build/kitchen-sink.html It's not that difficult to implement. Hope it helps!