8

I'm building a small and minimal code editor for HTML/CSS/js in simple Javascript. There is a problem when you write text in it. The problem is that i don't have the freedom to write the text wherever i want, because wherever i write/edit then the mouse pointer is automatically transported to the third line, and not remaining still at the point where i am writing.

enter image description here

For example, if i point the mouse somewhere in the editor and write a word, the mouse pointer immediately returns to another line (always at the beginning of the third line). So it stops me from writing the word where i want and the word gets written elsewhere. It's as if there were blocks in some points of the lines that prevent you from writing and i won't be able to write where i want.

ERROR: Initially, i thought the error is in HTML, then they pointed out that the problem is in applyColor() function, maybe it's Set cursor position to end of text code, i don't know. In fact, if i remove the applyColor() function, then problems are solved, but as a consequence what happens is that the text is no longer colored. But i need this piece of code (or something similar anyway), because it is part of the function to color the text. I therefore deduce that the problem is the applyColor() function, although i'm not 100% sure. So it should be a JavaScript problem:

  // CHANGE COLOR
  function changeColor() {
    var editor = document.getElementById("html");
    applyColoring(editor);
  
    // Set cursor position to the end of text
    var child = editor.children;
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(child[child.length - 1], 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    editor.focus();
  }

DEMONSTRATION OF THE PROBLEM: I'll show you when the problem occurs. In each of these cases, the mouse pointer is taken elsewhere and i won't be able to write where i want. i believe that by solving the unique problem in the applyColor() function, then all the problems will automatically be solved, because they all depend on the same unique problem.

  • If i try to write a word at the beginning of the third line enter image description here

  • If i try to write a word immediately after </h1> enter image description here

  • If i try to edit This is a Heading, it writes a word between <h1> and This enter image description here

  • If i try to write a word immediately after </p> enter image description here

  • If I previously write any word in the third line (for example aaaaaaa), and then try to write a new word in the first line immediately after </h1>. enter image description here

But the mouse pointer can also be moved in other areas (within those 3 staves) which I haven't written about. Of course it all stems from just one problem

WHAT WOULD I WANT? I would like that when i write a word (wherever it is written, in any position), the mouse pointer should remain stationary/stopped at the last written word (as any editor or chat works for example), and should not automatically move to the third line (like the photos above). Of course some words must remain colored (as already happens in my code). For example like this, i would like to get this:

enter image description here

Naturally, if I insert new lines in the HTML code editor, the pointer, instead of moving to the third line, will move to the fourth, fifth and so on. Therefore the problem should be solved by also evaluating the insertion of new future lines

How can i have the freedom to write and modify editor code wherever I want and avoid moving the pointer to other lines? So, how should the applicolor() function be fixed?


UPDATE: Aware that the problem is almost impossible to solve, i would also like a simpler solution with CODEMIRROR, because perhaps it is the most sensible and right one

function applyColoring(element) {
  var keywords = ["DIV", "SPAN", "H1", "P"];
  var keywords2 = ["CLASS", "ID"];

  var newHTML = "";
  // Loop through words
  str = element.innerText;
  (chunks = str
    .split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
    .filter(Boolean)),
  (markup = chunks.reduce((acc, chunk) => {
    acc += keywords.includes(chunk.toUpperCase()) ?
      `<span class="statement">${chunk}</span>` :
      `<span class='other'>${chunk}</span>`;
    return acc;
  }, ""));
  element.innerHTML = markup;
}

// CHANGE COLOR
function changeColor() {
  var editor = document.getElementById("html");
  applyColoring(editor);

  // Set cursor position to the end of text
  var child = editor.children;
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(child[child.length - 1], 1);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  editor.focus();
}

// PREVIEW
const elHTML = document.querySelector("#html");
//const elCSS = document.querySelector("#css");
//const elJS = document.querySelector("#js");
const elPreview = document.querySelector("#preview");

function showPreview() {

  const html = elHTML.textContent;
  //const css = `<style>${elCSS.textContent}</style>`;
  //const js = `<scr` + `ipt>${elJS.textContent}</scr` + `ipt>`;
  const dataURL = "data:text/html;charset=utf-8," + encodeURIComponent(html);

  changeColor();

  elPreview.src = dataURL;
}

changeColor()
showPreview()
#html {
  width: 456px;
  height: 267px;
  padding: 10px;
  background-color: #444;
  color: white;
  font-size: 14px;
  font-family: monospace;
  white-space: pre;
}

.statement {
  color: orange;
}

#editor {}

#preview {
  display: block;
  width: 100%;
}
<div id="html" contenteditable="true" oninput="showPreview();" onchange="changeColor();">&lt;h1>This is a Heading&lt;/h1> &lt;p>This is a paragraph.&lt;/p>
</div>

<h3>PREVIEW</h3>
<div class="preview-area">
  <iframe id="preview"></iframe>
</div>

14
  • I would suggest temporarily disabling showPreview() and changeColor() to start with, in case one of those is interfering. It might help to narrow down the cause... Commented Jan 1, 2024 at 2:17
  • 1
    @NickGris I tried disabling them. The problem still occurs. I think the problem is something in the html Commented Jan 1, 2024 at 2:32
  • I guess it could be getting confused because of the attempt to write tags inside the div - does it work OK if you just put plain text in there? I don't know if it's possible to use \uHHHH to get the < and > in there and if that would work any better... Commented Jan 1, 2024 at 2:54
  • 3
    The problem is caused by the Set cursor position to end of text code. You somehow have to rewrite it to focus on the end of the line instead of all text. If you remove the applyColor listener the problem does not occur. Commented Jan 1, 2024 at 5:06
  • 1
    Maybe this article will be helpful. Long story short, when a form element is changed, the browser automatically moves the cursor to the end. So you should save the cursor position before modification, and then restore cursor position after modification. You are adding span elements, so you may also need to account for the extra characters you've inserted.. giacomocerquone.com/keep-input-cursor-still Commented Jan 2, 2024 at 21:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.