user3371049 user3371049 - 1 month ago 13
Javascript Question

Repositionning the carret before inserting text via htmlbutton addon in Ckeditor instance

My goal using htmlbuttons addon for CKeditor is to insert the html code at the very beginning of the textbox content, despite the position of the carret. I adapted the script shown bellow (found here), but it does not work, so I need to know what could be wrong.

CKEDITOR.plugins.add( 'htmlbuttons',
{ init : function( editor )

{ for (name in CKEDITOR.instances) {
var instance = CKEDITOR.instances[name]; }


above I get the id (wich is the same as the name) - verified

function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}

function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}


above is the script I found here to reposition the carret (cursor).

var buttonsConfig = editor.config.htmlbuttons;
if (!buttonsConfig)
return;

function createCommand( definition )
{
return {
exec: function( editor ) {

instanceId = (instance.name);

setCaretToPos(document.getElementById(instanceId),0);


line above should position the carret at the beginning of ckeditor textbox, but it does not work.

editor.insertHtml( definition.html );
}
};
}

// Create the command for each button
for(var i=0; i<buttonsConfig.length; i++)
{
var button = buttonsConfig[ i ];
var commandName = button.name;
editor.addCommand( commandName, createCommand(button, editor) );

editor.ui.addButton( commandName,
{
label : button.title,
command : commandName,
icon : this.path + button.icon
});
}
} //Init

} );

Answer

This is a better solution:

Replace the line "SetCaretToPos..." with this code:

(function( cursorManager ) {                
var range = editor.createRange();
range.moveToPosition( range.root, CKEDITOR.POSITION_BEFORE_END );
//OR range.moveToPosition( range.root, CKEDITOR.POSITION_AFTER_START );
editor.getSelection().selectRanges( [ range ] );
}( window.cursorManager = window.cursorManager || {}));