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.
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;
}
}
});
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With