Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for and react to Ace Editor change events

Can anyone please give an example, of how the on change event works in ACE Editor (https://ace.c9.io/#nav=api&api=editor), with a simple getValue() when the there is an on change event and send the new text to a div? Would be much appreciated as there is no tutorials on how to use Ace Editor other than the documentation. Thanks

like image 664
Andrew O'Neill Avatar asked Mar 01 '16 19:03

Andrew O'Neill


1 Answers

see https://jsfiddle.net/ralf_htp/hbxhgdr1/ and http://jsfiddle.net/revathskumar/rY37e/

html

<div class="container">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">Editor</h3>
    </div>
    <div class="panel-body">
      <a href="#" onclick="update()">go</a>
      <div id="editor" onChange="update()">function foo(items) { var x = "All this is syntax highlighted"; return x; }
      </div>
    </div>
  </div>
  <div id="output">Output is here (click 'go' and write HTML and js in the editor) </div>
  <div class="text-center">---End of editor---</div>
</div>

javascript

var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
editor.getSession().on('change', function() {
  update()
});

function update() //writes in <div> with id=output
{
  var val = editor.getSession().getValue();
  var divecho = document.getElementById("output");
  divecho.innerHTML = val;
}

the function update() implements the onChange event that is associated with the editor. If the go-link is clicked and then a character is written in the editor the update()-function outputs the content of the editor in the <div> with id = output as html (innerHTML)

css

#editor {
  /** Setting height is also important, otherwise editor wont showup**/
  height: 300px;
}

#output {
  height: 100px;
}

https://ace.c9.io/ section Listenting to Events

See also this thread ace editor onchange not working

like image 185
ralf htp Avatar answered Sep 23 '22 12:09

ralf htp