add custom class to wysihtml5 text editor
Asked Answered
E

1

6

I'd like to be able to add a button that adds my own custom class. I don't see this in the documentation anywhere but seems like a common request.

For example.

Highlighting "Some Text" and pressing the button "Custom Class" will add

<p class="wysiwyg-custom-class">Some Text</p>

Embolic answered 13/12, 2012 at 22:25 Comment(2)
1,2 ,3, bonus this is documentation you looked for ?Hungry
As stated in the title this is for wysihtml5 text editor. I need to be able to highlight the text and add a custom class. It's more complicated than just adding a class though.Embolic
T
5

Define new command, my example is based on ForeColor:

(function(wysihtml5) {
    
  wysihtml5.commands.setClass = {
    exec: function(composer, command, element_class) {
        element_class=element_class.split(/:/);
        element=element_class[0];
        newclass=element_class[1];
      var REG_EXP = new RegExp(newclass,'g');
    //register custom class
      wysihtml5ParserRules['classes'][newclass]=1;

      return wysihtml5.commands.formatInline.exec(composer, command, element, newclass, REG_EXP);
    },

    state: function(composer, command, element_class) {
        element_class=element_class.split(/:/);
        element=element_class[0];
        newclass=element_class[1];
        var REG_EXP = new RegExp(newclass,'g');
      return wysihtml5.commands.formatInline.state(composer, command, element, newclass, REG_EXP);
    }
  };
})(wysihtml5);

usage:

HTML:

<div id="uxToolbar">
   <button data-wysihtml5-command="setClass" data-wysihtml5-command-value="span:my-wysihtml5-custom-class" type="button" title="View HTML" tabindex="-1" class="btn btn-mini">
       My class
   </button>
</div>

so as you can see value is from two parts: element:class

DEMO

Tottering answered 14/12, 2012 at 0:4 Comment(2)
I got an error: Uncaught ReferenceError: wysihtml5ParserRules is not defined, using your code.Reneerenegade
@user437797 I update fiddle demo, to get javascript with correct mime types: jsfiddle.net/oceog/nkkek so my code works fine. If you have the problem with modifications of this code - ask new question.Hungry

© 2022 - 2024 — McMap. All rights reserved.