Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS classes and an ID to paragraphs in CKEditor?

Tags:

ckeditor

How would I add custom classes or an ID to text paragraphs in CKEditor? I would want to load the possible classes from DB and write them to whichever list they would be in as CKE is being loaded. The ID's would simply be made up on the spot. The classes and ID's would be used for things like marking a piece of text as a footnote or a caption.


Just to be clear, I don't want to change the visible style the text using the dropdown boxes, I want to add CSS classes that can be used to style the element After it has been saved -depending on where it is used.

like image 436
Joel Peltonen Avatar asked Sep 04 '12 06:09

Joel Peltonen


Video Answer


1 Answers

Here you go. This code will number your paragraphs with subsequent ids and it also will append a custom class to each paragraph which hasn't been assigned yet.

var idCounter = 0,
    pClass = 'myCustomClass',
    pClassRegexp = new RegExp( pClass, 'g' );

CKEDITOR.replace( 'editor1', {
    on: {
        instanceReady: function() {
            this.dataProcessor.htmlFilter.addRules({
                elements: {
                    p: function( element ) {
                        // If there's no class, assing the custom one:
                        if ( !element.attributes.class )
                            element.attributes.class = pClass;

                        // It there's some other class, append the custom one:
                        else if ( !element.attributes.class.match( pClassRegexp ) )
                            element.attributes.class += ' ' + pClass;

                        // Add the subsequent id:
                        if ( !element.attributes.id )
                            element.attributes.id = 'paragraph_' + ++idCounter;
                    }
                }
            });
        }
    }
});
like image 78
oleq Avatar answered Nov 14 '22 05:11

oleq