Reputation: 2011
I'm not to insert HTML into ace editor via link onclick with jquery. So far as I have been successful, even when trying this script:
Javascript:
function insertAtCaret(areaId,text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false ) );
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
range.moveStart ('character', strPos);
range.moveEnd ('character', 0);
range.select();
}
else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
HTML Link:
<a href="#" onclick="insertAtCaret('ace_text-input','<h1></h1>');return false;">Click Here to Insert</a>
Trying to achieve the effect similar to a WYSIWYG editor, only raw HTML is shown in the editor.
Upvotes: 0
Views: 1278
Reputation: 24159
use session.insert method to add text to ace
var pos = editor.selection.getCursor()
var end = editor.session.insert(pos, text)
editor.selection.setRange({start:pos,end:end})
you can also use snippetManager as described in https://stackoverflow.com/a/26102713/1743328 and insert a snippet like '<h1>$0</h1>'
Upvotes: 2