Search code examples
phpclassckeditorckfinder

Force ckeditor to add a class


I'm using CKEditor in combination with CKFinder to control the images of a slideshow. in order for the slideshow to make everything work the images need "Slideshow-Sponsors" as class added to them. ATM if you add a image you need to add the class for every image again. i would like that CKEditor adds the class automaticly but in that instance only.

i've read this tread: Force CKEditor to add a class to p-tags carefully but i'm not able to get it to work.

so this is what my code looks like

<form action="verwerken.php" method="post">
   <div class="Slideshow-container w3-half w3-content w3-display-container" id="Slideshow">
      <textarea style="width: 100%" rows="5" id="sponsorsideshow" name="sponsorslideshow">
         <?php echo $sponsorslideshow; ?>
      </textarea>
      <script type="text/javascript">
         var editor = CKEDITOR.replace( 'sponsorslideshow', {
            filebrowserBrowseUrl : 'ckeditor/ckfinder/ckfinder.html',
            filebrowserImageBrowseUrl : 'ckeditor/ckfinder/ckfinder.html?type=Images',
            filebrowserFlashBrowseUrl : 'ckeditor/ckfinder/ckfinder.html?type=Flash',
            filebrowserUploadUrl : 'ckeditor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
            filebrowserImageUploadUrl : 'ckeditor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
            filebrowserFlashUploadUrl : 'ckeditor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
          });
          editor.dataProcessor.htmlFilter.addRules({
             elements :{
                img : function( element ){
                   if ( element.className.indexOf("Slideshow-Sponsors") < 0){
                      element.className += 'Slideshow-Sponsors';
                   }
                }
             }
          });
          CKFinder.setupCKEditor( editor, '../' );
      </script>
      <button type="submit"">Opslaan</button>
   </div>
</form>

The expected results are that CKEditor adds class="Slideshow-Sponsors" to every img but only in that instance. there are other instances running on the same page which alse uses images so adding in a config doesn't provide a good solution. but the actual result is that ckeditor doesn't add the class.


Solution

  • Rules should be put in an instanceReady event and you should use hasClass and addClass functions.

    editor.on('instanceReady', function(evt) {
        this.dataProcessor.htmlFilter.addRules({
            elements: {
                img: function(element) {
                    if (!element.hasClass('Slideshow-Sponsors')) {
                        element.addClass('Slideshow-Sponsors');
                    }
                }
            }
        });
    });