javascripthighlight.js

Cursor position resets in in text box after the highlight.js highlight function is called


I am trying to make a custom code editor using HTML CSS and JavaScript and I want the code contained in the editable code block to be highlighted and that's where highlight.js comes in.

Every time the user types in something inside the block it renders in an iframe (think W3 School) and I have successfully made the code in the code block highlight but what happens is that the cursor position in the code block resets. How can I stop the cursor position from resetting without having to constantly keep track of its position? This is an image that illustrated what I've mentioned up to now

        hljs.initHighlightingOnLoad();


        const editor = document.querySelector(".editor");
        const iframe = document.querySelector("iframe");
        const codeSubmitBtn = document.querySelector(".code-editor-btn");


        editor.addEventListener('keyup', () => {
            let html = editor.getAttribute('data-prerequisite') + editor.textContent;
            iframe.src = `data:text/html;charset=utf-8, ${encodeURI(html)}`;

          document.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightBlock(block);
            });

        });
<!DOCTYPE html>
<html lang="en">

<head>

    <title>Code editor</title>
<!-- THE HIGHLIGHT JS STUFF-->
    <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.16.2/build/styles/default.min.css">

    <script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.16.2/build/highlight.min.js"></script>


</head>


<body>

    <div class="main-editor">
        <pre>
    <code class="editor html" contenteditable="true"
    data-prerequisites="<li>Hi this needs to be in</li>">&lt;h1&gt; How are you &lt;/h1&gt;</code>
</pre>
        <iframe class="second"></iframe>
    </div>

    <button class="code-editor-btn" contenteditable="false">submit!</button>

</body>
</html>


Solution

  • Actually highlight.js is not intended to be used like that. However, there are might be some workaround like tracking cursor position and move it to the place where it was, but it's not really worth it. Try something more convenient for this like "Ace Highlight"