Home    Articles

 

How to add inline CKEditor on ui droppable dynamically created elements

 

Some time ago i had to create some dynamically html blocks with ckeditor on them but i got two errors: 

1. Uncaught TypeError: Cannot call method 'toLowerCase' of undefined using Ckeditor

This error is becouse you're are trying to use ckeditor on some wrong element that may not exist in your html.

2. Uncaught The editor instance "editable1" is already attached to the provided element.

My code with this error:

/// ....lot of jquery code

 $("#maincontent").droppable({
        drop: function(event, ui) {
            var blockId = ui.draggable.attr('block-id');
            ui.draggable.html('<p contenteditable="true">I\'m editable!<div class="dragArea"></div></p>');
            ui.draggable.attr('contenteditable','true');
            CKEDITOR.inline( ui.draggable.get( 0 ) );  // this is the line with issues
        },
        over: function(event, ui) {}
    });

The second error apears becouse you are trying to add ckeditor on some html block that already has ckeditor on it. For me, somehow it worked to add multiple ckeditor on my html blocks but my sortable elements won't work anymore becouse of this error.

Here is my example with this error:  http://jsfiddle.net/0wp1gy7c/5/

How i solved this: 

On drop event i've added a new and UNIQUE id to the cloned / dropped element in order to instantiate ckeditor on it. CKEditor will not throw this error becouse another UNIQUE element has been created. This is the solution to solve this kind of error.

Here is the fixed code that keeps sortable in working state : http://jsfiddle.net/0wp1gy7c/7/ 

// ...lot of jquery code
    $("#maincontent").droppable({
        drop: function(event, ui) {
            var blockId = ui.draggable.attr('block-id');
            ui.draggable.removeAttr('block-id');
           if(typeof blockId !==  typeof undefined && blockId !== false) { 
	   			ui.draggable.html('<p contenteditable="true">I\'m editable!<div class="dragArea"></div></p>');
                ui.draggable.attr('contenteditable','true');
	   			ui.draggable.attr('id','editable'+blockId+'_'+blocksCounter);
	   			CKEDITOR.inline( 'editable'+blockId+'_'+blocksCounter ); 
	   			blocksCounter++;
	   		}
        },
        over: function(event, ui) {}
    });

First i took this simple example:  http://jsfiddle.net/RKPYw/ ...but i lost 1 day to get this working for me ( with sortable  lists ). 

Enjoy. 

 

by