Search code examples
javascripthtmliframeace-editorcodemirror

ACE Syntax highlighter for live code editor not working


So i am trying to build a code editor which shows output of html in iframe. but there is some trouble. i used codemirror before now i am using ACE but something goes wrong here as it keeps showing me "xxxxxx" and numbers. what is the correct way to use it?

<!DOCTYPE html>
<html>

  <head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.9/ace.js"></script>
   <style>
      #jsEditor{height:300px;}
   </style>
  </head>

  <body>  
     <div id="jsEditor"></div>
     <iframe id="frame"></iframe>
     <button onclick="refresh()">Click</button>
     <script type="text/javascript">
         var e=ace.edit("jsEditor");
         e.getSession().setMode("ace/mode/html");
         e.setTheme("ace/theme/xcode");
         e.getSession().setTabSize(2);
         e.renderer.setShowGutter(false);

         function refresh(){
            var textval=document.getElementById('jsEditor').textContent;
            document.getElementById('frame').srcdoc=textval;
          }     
     </script>
  </body>

</html>

[This is the output i get ][2]

https://jsfiddle.net/fc0cjo9z/


Solution

  • Ace renders to dom only the visible portion of the text, and adds some nodes that do not correspond to any text. So instead of document.getElementById('jsEditor').textContent you need to call the getValue() method of the editor. in your example change the line with textContent to

    var textval=e.getValue();