At my current project we needed to add a text highlight function button to the Rich Text Editors (RTE) ribbon, so when the user click on the button a selected text in the RTE, is wrapped with a predetermined HTML tag, indicating the text has been highlighted. Like <span css=”highlight”>the selected text</span>
The thing we need is:
1) The button in the ribbon, only showed when we are in the context of the RTE
2) The JavaScript snippet the will interact with the RTE
3) A feature the adds the ribbon button and the JavaScript to the page
The button is added to the style group like this:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="Ribbon.Demo.HighlightText"
Location="CommandUI.Ribbon"
Title="Insert Tooltips">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.EditingTools.CPEditTab.Styles.Controls._children">
<Button
Id="Ribbon.Demo.HighlightText.Button"
Sequence="12"
LabelText="High light text"
Alt="High light text"
TemplateAlias="o1"
Image32by32="/_layouts/RTE.Demo/images/highlight32.png"
Command="Ribbon.Demo.HighlightText.Command"
ToolTipTitle="High light text"
/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="Ribbon.Demo.HighlightText.Command"
CommandAction="javascript:HighLightText();"
EnabledScript="true" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
</Elements>
The JavaScript snippet looks like this:
function HighLightText() {
var rng = RTE.Cursor.get_range().$3_0;
var selectedText = RTE.Cursor.s_range.get_text();
RTE.Cursor.get_range().deleteContent();
var d = rng.ownerDocument;
var a = d.createElement("span");
a.innerHTML = selectedText;
a.setAttribute("class", "highlight");
SP.UI.UIUtility.insertAfter(a, rng);
}
Download the full project here