Jump to content

How to properly add content to CKEditor?


Safety1st

Recommended Posts

Posted

I'd like to add some HTML content to CKEditor editing area after user clicks on something.
Previously it was done by the following code:

var editor = ips.ui.editor.getObj($('[data-role="replyArea"] [data-ipsEditor]'));
if (editor) {
    editor.unminimize();
    ...
    editor.insertHtml(html);
    editor.focus();
}

But this method doesn't work properly on the last IPS4 builds. I get the weird error right after executing editor.insertHtml(html):

"q is undefined"

 

Posted

The code doesn't work correctly if editor's window was not activated first. I get 'range is undefined' error. Here is the video :)

Here is the code :)

 try {
            var editor = ips.ui.editor.getObj($('[data-role="replyArea"] [data-ipsEditor]'));
            if (editor) {
                editor.unminimize();
                var url = $(this).attr('data-ipshover-target').split('do=hovercard')[0];
                var id = url.replace(new RegExp("(.*)/profile/([0-9]+)-(.*)", 'g'), "$2");
                var hovercard = url + 'do=hovercard';
                url = url.substr(0, url.length - 1);
                var name = $(this).text();
                var a = $('<a>').attr({
                    'contenteditable': 'false',
                    'href': url,
                    'data-ipshover-target': hovercard,
                    'data-mentionid': id,
                    'data-ipshover': ''
                }).text('@' + name);
                var div = $('<div>').append(a);
                var aHTML = div.html().trim();
                editor.insertHtml(aHTML);
                editor.focus();
            }
        }
        catch (e) {
            console.log(e.message);
        }

editor.insertHtml('<b>test</b>') leads to the same result.

Posted
setTimeout(function(){
	editor.insertHtml(aHTML);
	editor.focus();
}, 200);

you need to setup some sort of timeout/delay. there are better ways to do this, but this gives you an idea. what is happening, when you call editor.unminimize(), the editor isn't fully initialized yet, so the editor.insertHtml()/focus() call are causing an error.

Posted

Insert the HTML in a callback function passed to unminimize. Here is how we insert stuff into the warn form as a random example (modified slightly for clarity).

					editor.unminimize( function(){
						editor.insertHtml( response.notes );
					});

 

Archived

This topic is now archived and is closed to further replies.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...