Damjan Pavlica Damjan Pavlica - 10 months ago 148
Javascript Question

Is it possible to make a textarea an ACE editor?

I saw a similar topics here, but I couldn't find an answer. I am trying to connect Ace editor to

, but unsuccessfully. Then I found that "ace works only on divs."

I prefer to connect editor to textarea, not to div. So, is it possible to connect Ace to textarea?

Thanks in advance!

Answer Source

This depends on what you want to do with the textarea after replacing it, but is easy to do with several lines of js

// create new ace instance
var editor = ace.edit(document.createElement("div"))
// set size
editor.container.style.height = textArea.clientHeight + "px";
editor.container.style.width = textArea.clientWidth + "px";
// replace textarea with the editor
textArea.parentNode.replaceChild(editor.container, textArea)
// trigger redraw of the editor

and to replace editor with textarea

var value = editor.getValue()
var start = editor.session.doc.positionToIndex(editor.selection.getRange().start)
var end   = editor.session.doc.positionToIndex(editor.selection.getRange().end)
textArea.value = value
textArea.setSelectionRange(start, end)
editor.container.parentNode.replaceChild(textArea, editor.container)

you also can try to use textarea extension from ace https://github.com/ajaxorg/ace/blob/master/lib/ace/ext/textarea.js