skip to Main Content

I have a problem with a Javascript script to color text. There are strings set for coloring, but the word is only colored when I press the "space" key on the keyboard. If i write the word, it doesn’t color. If I write the word and press the space key it becomes colored.

I would like to color the word immediately as i write it, without waiting to press the space button. For example, i set that HELLO should be colored. I would like it to color immediately as soon as I finish pressing the final O, and not when i type HELLO (with a final space).

The problem occurs when you try to manually write something in the code panel, for example if you write Hello. The problem lies in the changeColor() function, there is a Keyup Event and a Space Key Pressed.

I tried to remove the part of the code that concerns the EventListener("keyup"… and the keycode, but everything breaks and doesn’t work. I am new to Javascript, I can’t solve it.

index.html

  <div id="editor" 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-window"></iframe>
    </div>

style.css

#editor {
  width: 400px;
  height: 100px;
  padding: 10px;
  background-color: #444;
  color: white;
  font-size: 14px;
  font-family: monospace;
  white-space: pre;
}
.statement {
  color: orange;
}

javascript.js

function applyColoring(element) {
    var keywords = ["DIV", "DIV", "H1", "H1", "P", "P", "HELLO", "<", ">", "/"];
  
    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() {
    // Keyup event
    document.querySelector("#editor").addEventListener("keyup", (e) => {
      // Space key pressed
      if (e.keyCode == 32) {
        applyColoring(e.target);
  
        // Set cursor postion to end of text
        //    document.querySelector('#editor').focus()
        var child = e.target.children;
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length - 1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        this.focus();
      }
    });
  }
  
changeColor()
applyColoring(document.getElementById('editor'));


//PREVIEW
function showPreview() {
    var editor = document.getElementById("editor").innerText;
  
    // var cssCode =
    //  "<style>" + document.getElementById("cssCode").value + "</style>";
    // var jsCode =
    //  "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
    
    var frame = document.getElementById("preview-window").contentWindow.document;
    document.getElementById("preview-window").srcdoc = editor;
    frame.open();
    //frame.write(htmlCode + cssCode + jsCode);
    frame.write(editor);
    frame.close();
  }
  
  showPreview()

2

Answers


  1. You were on the right track: you don’t have to delete the whole ‘keyup’ event listener code—just remove the if-statement surrounding the logic. The if (e.keyCode == 32) checks to see if the Space key was pressed, so if you want that part of the code to run when any key is pressed, simply don’t use the if-statement.

    function changeColor() {
        // Keyup event
        document.querySelector("#editor").addEventListener("keyup", (e) => {
          // // Space key pressed
          // if (e.keyCode == 32) {
            applyColoring(e.target);
      
            // Set cursor postion to end of text
            //    document.querySelector('#editor').focus()
            var child = e.target.children;
            var range = document.createRange();
            var sel = window.getSelection();
            range.setStart(child[child.length - 1], 1);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            this.focus();
          // }
        });
      }
    
    Login or Signup to reply.
  2. to coloring the word immediately after typing the last letter Instead of relying on the "keyup" event you can use the "input" event
    This will allow you to update the color immediately after each letter is typed

    function applyColoring(element) {
      var keywords = ["DIV", "H1", "P", "HELLO", "<", ">", "/"];
    
      var text = element.textContent;
      var markup = "";
    
      for (var i = 0; i < text.length; i++) {
        var char = text[i];
        markup += keywords.includes(char.toUpperCase())
          ? `<span class="statement">${char}</span>`
          : `<span class='other'>${char}</span>`;
      }
    
      element.innerHTML = markup;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search