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>

dardub
  • 3,166
  • 5
  • 29
  • 31
  • [1](https://developer.mozilla.org/en-US/docs/DOM/Element.getElementsByClassName),[2](https://developer.mozilla.org/en-US/docs/DOM/element.classList) ,[3](https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener), [bonus](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures) this is documentation you looked for ? – zb' Dec 13 '12 at 23:32
  • 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. – dardub Dec 15 '12 at 01:02

1 Answers1

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

zb'
  • 8,071
  • 4
  • 41
  • 68
  • I got an error: Uncaught ReferenceError: wysihtml5ParserRules is not defined, using your code. – Akim Kelar Apr 27 '13 at 07:44
  • @user437797 I update fiddle demo, to get javascript with correct mime types: http://jsfiddle.net/oceog/nkkek/ so my code works fine. If you have the problem with modifications of this code - ask new question. – zb' Apr 27 '13 at 15:14