Search code examples
javascriptace-editor

Ace editor mode not working


I am trying to get syntax highlighting working but when changing the mode it doesn't work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/monokai.js"></script>
    <script="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/mode-javascript.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>
    <script src="scripts.js"></script>

scripts.js

var html = ace.edit("htmlEditor");
var css = ace.edit("cssEditor");
var js = ace.edit("jsEditor");

html.setTheme("ace/theme/monokai");
css.setTheme("ace/theme/monokai");
js.setTheme("ace/theme/monokai");

var JavaScriptMode = ace.require("ace/mode/javascript").Mode;
js.session.setMode(new JavaScriptMode());

Solution

  • You have a typo in your html <script=" also scripts for theme and modes must be inserted after ace.js

    It is better to pass names to ace and let it load modes and themes by itself

    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>
    <div id="htmlEditor">&lt;html&gt;</div>
    <div id="cssEditor">.css { color: red }</div>
    <div id="jsEditor">var js</div>
    <style>
    html, body {
        height: 100%;
    }
    #htmlEditor, #cssEditor, #jsEditor  {
    height:30%
    }
    </style>
    <script>
    
    var html = ace.edit("htmlEditor");
    var css = ace.edit("cssEditor");
    var js = ace.edit("jsEditor");
    
    html.setTheme("ace/theme/monokai");
    css.setTheme("ace/theme/monokai");
    js.setTheme("ace/theme/monokai");
    
    html.session.setMode("ace/mode/html");
    css.session.setMode("ace/mode/css");
    js.session.setMode("ace/mode/javascript");
    
    </script>