When a user clicks on a contenteditable element inside my page-builder, I trigger a click-event that initialises a Shared CKEditor
instance.
The problem is that I lose the caret-position and CKEditor places this cursor to the beginning of the text?
I would like to restore the caret position to the same position the user clicked before initialization. This is mostly in the middle of the text.
To achieve this I need two steps:
- Get the caret position before initializing the CKEditor
- Use the caret position in an CKEditor 'instanceReady' event and place the pointer back.
I have found this piece of code (from here):
editor.focus(); var selection = editor.getSelection(); var range = selection.getRanges()[0]; var pCon = range.startContainer.getAscendant({p:2},true); //getAscendant('p',true); var newRange = new CKEDITOR.dom.range(range.document); newRange.moveToPosition(pCon, CKEDITOR.POSITION_BEFORE_START); newRange.select();
But this only works when the editor is already instantiated. In my situation I start without an editor.
Any way to get this done?
2 Answers
Answers 1
Do you simply want to initialize the editor so the cursor position is where they clicked to start editing?
You can use the selection range and insert a placeholder into the original HTML, before starting the editor.
After starting the editor, find the placeholder in the editor content, remove it, and place the caret there. The placeholder could be as simple as <span class="caret-placeholder"></span>
.
Answers 2
With jQuery, you can get the cursor position using:
$('#element').prop("selectionStart");
Native JS would be:
document.getElementById('#element').selectionStart;
(You would need additional code if you have to support IE8 and below.)
On your click event, you need to get the CKEditor instance:
CKEDITOR.instances
Then you should be able to use your code to set the cursor position.
0 comments:
Post a Comment