Reputation: 363
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 caret. I adapted the script shown below (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 (which 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 caret (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 caret 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
} );
Upvotes: 0
Views: 116
Reputation: 363
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 || {}));
Upvotes: 0
Reputation: 363
I found my answer - replace the line "SetCaretToPos..." with this code:
editor.focus();
var selection = editor.getSelection();
var range = selection.getRanges()[0];
var pCon = range.startContainer.getAscendant('p',true);
var newRange = new CKEDITOR.dom.range(range.document);
newRange.moveToPosition(pCon, CKEDITOR.POSITION_BEFORE_START);
newRange.select();
that's it. It inserts the code at the very begining - disregarding the cursor position.
Upvotes: 1