There are situations where you might need to create new tabs and buttons on the ribbon and all you have to work with is javascript.

If you ever find yourself in such a situation here is a small example of javascript code to create  new button and a new tab:

ExecuteOrDelayUntilScriptLoaded(function () { //Wait for sp.ribbon.js to be loaded
        var pm = SP.Ribbon.PageManager.get_instance();
        pm.add_ribbonInited(function() { //Adds a handler to the handle the RibbonInited event.
		var ribbon = (SP.Ribbon.PageManager.get_instance()).get_ribbon();
	        createTab(ribbon);
        });
}, 'sp.ribbon.js');

function createTab(ribbon) {
    var tabId = "Your.Tab.Id";
    var tabGroupId = "Your.Tab.Group.Id";
    var tabText = "Your Tab Text";
    var tabGroupText = "Your Tab group text";
    var tabButtonText = "Your Button text";

    var tab = new CUI.Tab(ribbon, tabId, tabText, "Tab Description", 'Tab.Attach.Command', false, '', null, null);
    ribbon.addChild(tab);

    var group = new CUI.Group(ribbon, tabGroupId, tabGroupText, "Group Description", 'Tab.Attach.Group.Command', null);
    tab.addChild(group);

    var layout = new CUI.Layout(ribbon, 'Tab.AttachNews.Layout', 'The Layout');
    group.addChild(layout);

    var section = new CUI.Section(ribbon, 'Tab.AttachNews.Section', 2, 'Top'); //2==OneRow
    layout.addChild(section);
    var controlProperties = new CUI.ControlProperties();
    controlProperties.Command = 'Tab.AttachNews.Button.Command';
    controlProperties.Id = 'Tab.AttachNews.ControlProperties';
    controlProperties.TemplateAlias = 'o1';
    controlProperties.ToolTipDescription = tabButtonText;
    controlProperties.Image32by32 = '_layouts/15/images/discoveryExport_32x32.png';
    controlProperties.ToolTipTitle = tabButtonText;
    controlProperties.LabelText = tabButtonText;
    var button = new CUI.Controls.Button(ribbon, 'Tab.AttachNews.Button', controlProperties);
    button.set_enabled(true);
    var controlComponent = button.createComponentForDisplayMode('Large');
    var row1 = section.getRow(1);

    row1.addChild(controlComponent);
    group.selectLayout('The Layout');

    SelectRibbonTab(tabId, true); //Mark new tab as selected
    controlComponent.set_enabled(true);
    var btn = button.getDOMElementForDisplayMode("Large");
    $(btn).click(function () { /* your code */ }); //attach click event to the newly created ribbon button
}

Ribbon Button


1 Comment

JAMES · May 2, 2018 at 8:39 am

Dear Daniel,
Interesting code but when i add code Inside click function, nothing happen. Can you post or send me by email a sample code on what to put Inside click function?
Regards.
Stephane

Leave a Reply to JAMES Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: