Search code examples
javascripthtmlcsssyntax-highlightingcodemirror

Is it possible to have syntax highlighting for HTML/CSS/JS in <textarea>?


Here's a pen of what I mean:

http://codepen.io/archiehicklin/pen/oZQdEG

 <textarea id="html" placeholder="HTML"></textarea>
    <textarea id="css" placeholder="CSS"></textarea>
    <textarea id="js" placeholder="JS"></textarea>
<iframe id="code"></iframe>

Trying to build a small offline wysiwyg editor and was wondering if it's possible to have some form of real-time syntax highlighting for the code input into textarea - similar to codepen or jsfiddle.

I've come across the Codemirror library but it doesn't seem like it would work for live input.


Solution

  • You cannot directly control syntax highlighting in a textarea. You can try JS libraries like http://www.cdolivet.com/editarea/ or if you just wnat to do it all by yourself, you can go for contenteditable .

    Contenteditable is an html Attribute that enables textarea like editing in any element like div , span etc.

    Although you will have to use a lot of javascript to interpret the language and highlight it accordingly.

    <div contenteditable="true" style="width:100%;height:200px;border:1px solid #000">
    <b>This is bold text</b><br/>
    <u>This is underlined text</u><br/>
    and so on..<br/>
    <font color="#f00">class</font> <font color="#0f0">Sample</font><br/>
    <em>{</em><br/>
    </div>

    UPDATE

    If planning some third party libraries you can go for highlight.js: https://highlightjs.org/

    It can be integrated with your contenteditable.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/languages/php.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/purebasic.min.css" />
    <script>hljs.initHighlightingOnLoad();</script>
    <pre><code class="html">class test {}</code></pre>