I am having this problem. I am inserting input elements in a contenteditable div. The caret is in the input at the last position. I would like some help how to move the cursor right after that input by executing some function. You will see in my code that I have to click (justInserted.click()
) to make some resizing happen. If I remove the justInserted.focus()
then the caret is always at the start of the contenteditable. I would like to have a function that finds that the caret is in a specific input in the contenteditable and when I call it, it will put the caret right after that specific input. Any help is appreciated :)
My insert at caret looks like this:
this.insertNodeAtCursor = function(node) {
var sel, range, html;
function containerIsEditable(selection) {
return $(selection.anchorNode).parent().hasClass("editable");
}
if (window.getSelection) {
sel = window.getSelection();
// only if it is a caret otherwise it inserts
// anywhere!
if (containerIsEditable(sel) && sel.getRangeAt
&& sel.rangeCount) {
var previousPosition = sel.getRangeAt(0).startOffset;
sel.getRangeAt(0).insertNode(node);
}
}
else if (document.selection
&& document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data
: node.outerHTML;
range.pasteHTML(html);
}
};
and the function that adds the input is this:
this.addInput = function(suggestEntry, query) {
var id = suggestEntry.id;
var nodeClass = suggestEntry.nodeClass;
var uuid = suggestEntry.uuid;
var clause = null;
if (nodeClass === "Entity"){
clause = new Entity();
clause.uuid = uuid;
clause.id = id;
clause.text = suggestEntry.text;
}
var input = clause.toEditorElementHtml();
this.insertNodeAtCursor(input);
var rand = Math.floor((Math.random() * 1000000) + 1);
input.setAttribute('id', "rand-" + rand);
$rootScope.$broadcast("remove:query",query);
var autoSizingInputs = $('input[autosize="autosize"]');
var justInserted = $('#rand-' + rand);
$compile(autoSizingInputs)($scope);
justInserted.focus();
justInserted.click(); // a bit hacky :/
$(justInserted).val($(justInserted).val() + "");
};