Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class or attribute automatically to img tags in CKEditor?

I'm using CKEditor version 3.6

I want to automatically add class="newsleft" to any image tag added through the WYSIWYG.

I've seen a few posts that mention dataProcessor but have no idea which file this should be added or how to do it.

Can someone tell me where I would place the following code?

editor.dataProcessor.htmlFilter.addRules(
{
    elements:
    {
        img: function( element )
        {
            if ( !element.attributes.alt )
                element.attributes.alt = 'An image';
        }
    }
} );
like image 741
user2286483 Avatar asked Sep 17 '13 15:09

user2286483


1 Answers

Basically put it in instanceReady listener and it will be fine (3.x and 4.x) (fiddle):

CKEDITOR.replace( 'editor', {
    plugins: 'wysiwygarea,toolbar,sourcearea,image,basicstyles',
    on: {
        instanceReady: function() {
            this.dataProcessor.htmlFilter.addRules( {
                elements: {
                    img: function( el ) {
                        // Add an attribute.
                        if ( !el.attributes.alt )
                            el.attributes.alt = 'An image';

                        // Add some class.
                        el.addClass( 'newsleft' );
                    }
                }
            } );            
        }
    }
} );

CKEDITOR.htmlParser.element.addClass is available since CKEditor 4.4. You can use this.attributes[ 'class' ] prior to that version.

like image 157
oleq Avatar answered Sep 28 '22 15:09

oleq