Search code examples
javascripthtmlcsscontenteditable

How to make user input unaffected by span elements color style


I have some words in a content editable <div> that needs to be a different color from the rest of the text. The problem is that I don't want the user to be able to use the different color style and they should still be able to delete the blue word.

<div id="textarea" contenteditable>Hello world<span style="color: blue">!</span>
</div>

Is it possible for the users' input to be unaffected by the color style?


Solution

  • You haven't really provided enough for us to go on - eg. what are the rules which determine what is blue and what is not? Is the blue text always an exclamation mark? Does it always come at the end?

    What it sounds like you will need is to build a simple lightweight code editor and apply the rules you desire. The way this works is you create a transparent editable div in the same space as a "display" div. The content of the editable textarea is invisible and the contents of the "display" div are visible. For every key stroke, you take the content of the editable textarea and write it to the "display" div and apply any custom rules. Here's a simple fiddle showing what I mean:

    https://jsfiddle.net/ymdrfupb/1/

    const editable = document.querySelector('.editor > [contenteditable]');
    const display = document.querySelector('.editor > .display');
    
    function setDisplayContent(text) {
      // wrap any non-alphanumeric trailing characters with a blue span
      display.innerHTML = text.replace(/([^\w]+)$/, '<span class="blue">$1</span>');
    }
    
    editable.addEventListener('input', (ev) => {
      setDisplayContent(ev.target.innerHTML);
    });
    
    setDisplayContent(editable.innerHTML);