tags:

views:

245

answers:

2

Is it possible to dynamically change the loaded stylesheet for a ckeditor instance?

i.e. i have a ckeditor instance with the following config: CKEDITOR.replace('_content', {"resize_enabled":true, "customConfig":"/kmt/js/ckeditor_config.js","contentsCss":"/custom/ckeditorstyle.css","contentWidth":"240"});

Not very complicated. Afterwards i want to allow the user to dynamically change the contentscss attribute...

A: 

You could combine the code given in the answer to this SO question (How to dynamically add style sheets during runtime) with the accepted answer to this SO question (How to access the body element of a CKEditor instance in JavaScript).

Pekka
+1  A: 

Thanx to Pekka, I achieved the solution via:

$('#stylesheeetSelector').change(function() {
    $.post('/getStylesheet', {id: $(this).val()}, function(data) {
        for(i in CKEDITOR.instances) {
            var linkElement = $(CKEDITOR.instances[i].document.$).find('link');
            if (data.editorStylesheet > 0) {
                if (linkElement.length == 0) {
                    $(CKEDITOR.instances[i].document.$).find('head').append('<link rel="stylesheet" type="text/css" href="'+ data.editorStylesheet +'">');
                } else {
                    linkElement.attr('href', data.editorStylesheet)
                }
            } else if (linkElement.length > 0) {
                linkElement.remove();
            }
        }
    });
});

It works by fetching a JSON object filled with (amoungst other things) the stylesheet URL and sets (or removes if none present) the selected stylesheet...

Clean and simple!

Gekkie
Very nice, thanks for sharing this!
Pekka