Skip to content
Jeffrey Guenther edited this page May 13, 2016 · 25 revisions

Toolbar

To add a new button without modifying Trix, you could do something like:

buttonHTML = "<button type=\"button\" class=\"heading\" data-trix-attribute=\"heading\" title=\"Heading\">Heading</button>";
groupElement = Trix.config.toolbar.content.querySelector(".block_tools");
groupElement.insertAdjacentHTML("beforeend", buttonHTML);

Trix uses data attributes to determine how to respond to a toolbar button click.

Toggle Attribute

With data-trix-attribute="<attribute name>", you can add an attribute to the current selection. For example, to apply bold styling to the selected text the button is:

<button type="button" class="bold" data-trix-attribute="bold" data-trix-key="b" </button>

Trix will determine that a range of text is selected and will apply the formatting defined in Trix.config.textAttributes (found in text_attributes.coffee).

data-trix-key="b" tells Trix that this attribute should be applied when you use meta+b

If the attribute is defined in Trix.config.blockAttributes, Trix will apply the attribute to the current block of text.

<button type="button" class="quote" data-trix-attribute="quote"</button>

Clicking the quote button toggles whether the block should be rendered with <blockquote>.

Invoke Action

Internal actions are defined in editor_controller.coffee and consist of:

  • undo
  • redo
  • link
  • increaseBlockLevel
  • decreaseBlockLevel
<button type="button" class="block-level decrease" data-trix-action="decreaseBlockLevel"</button>

Invoke External Action

If you want to add a button to the toolbar and have it invoke an external action, you can prefix your action name with x-. For example, if I want to print a log statement any time my new button is clicked, I would set by button's data attribute to be data-trix-action="x-log"

<button type="button" data-trix-action="x-log"</button>

To respond to the action, I listen for trix-action-invoke. The event object has a property named actionName you can use to detect which external action was invoked.

document.addEventListener("trix-action-invoke", function(event) {
    if(event.actionName === "x-log"){
        console.log("Log called");  
    }
}
Clone this wiki locally