Reputation: 4228
I'm dynamically adding CKEditor instances (on click event) to some elements of my page using JQuery.
Problem 1: if the elements were already clicked they already have an attached instance of CKEditor and this will cause an error when trying to create a new one.
Problem 2: I don't have an id on these elements so don't know the name of the CKeditor instances in advance. In this case they will be automatically generated following a progressive counter, like 'editor1', 'editor2' and so on.
So I can't remove the instances by name and removing all the instances on each click event doesn't seem a right solution.
QUESTION: I'd like to remove the CKEditor instance right after I'm done editing an element. Any other suggestions to remove the instances on a clicked element if it already exists (without knowing the instance name) before (re)creating it.
Upvotes: 0
Views: 2246
Reputation: 15895
Considering the following HTML:
<div class="foo">Hello!</div>
<div class="foo">World!</div>
You can use such approach to dynamically create editor instances basing on div
elements. Once the instance is blurred, it's destroyed but any subsequent click on div
will create a new one:
function attachEditorToElement( element ) {
element.once( 'click', function() {
CKEDITOR.replace( element, {
height: 100,
plugins: 'wysiwygarea,toolbar,basicstyles',
on: {
instanceReady: function() {
// Focus the instance immediately.
this.focus();
},
blur: function() {
// Save the reference to element.
var el = this.element;
this.destroy();
// A new instance will be created if div is clicked.
// Note that this is a different element than the one passed to attachEditorToElement.
attachEditorToElement( el );
}
}
} );
} );
}
var divs = CKEDITOR.document.find( 'div.foo' );
// Create editor instances when div is clicked.
for ( var i = divs.count(); i--; )
attachEditorToElement( divs.getItem( i ) );
The inline way:
CKEDITOR.disableAutoInline = true;
function attachEditorToElement( element ) {
element.once( 'click', function() {
if ( element.getEditor() )
return;
element.setAttribute( 'contenteditable', true );
CKEDITOR.inline( element, {
plugins: 'floatingspace,toolbar,basicstyles',
on: {
instanceReady: function() {
// Focus the instance immediately.
this.focus();
},
blur: function() {
var el = this.element;
el.removeAttribute( 'contenteditable' );
this.destroy();
attachEditorToElement( el );
}
}
} );
} );
}
var divs = CKEDITOR.document.find( 'div.foo' );
// Create editor instances when div is clicked.
for ( var i = divs.count(); i--; )
attachEditorToElement( divs.getItem( i ) );
Upvotes: 2