20

What would be 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?

1 Answer 1

23

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 the editor won’t show up **/
  height: 300px;
}

#output {
  height: 100px;
}

https://ace.c9.io/, section Listening to Events

See also this question: Ace editor with an onchange event is not working

2
  • Minor suggestion: when binding to the "change" event, the update function can directly be passed without wrapping it in an extra function : editor.getSession().on('change', update);. Jun 23, 2021 at 15:06
  • The ace.c9.io link is (effectively) broken. Nov 22, 2022 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.