SharePoint 2013: Trigger Event With Ribbon Tab Changes

I needed to change the delete button on the ribbon on some specific App parts on SharePoint 2013, so looking around I found a post that shows how to trigger an event with each ribbon change by Dennis George which was of great help because it did exactly what I needed, to capture when a certain tab was selected. The issue? It doesn’t work on SharePoint 2013 because the CUI.Ribbon.prototype.$L is always undefined, so I started debugging the whole ribbon and found that to make the code work in SharePoint 2013 I just had to change $L with $1q_0 and that was it. So here’s the code to trigger an event each time there is a change on the SharePoint 2013 ribbon. Use it at will:


// Fires 'ribbontabselected' every time the ribbon selection changes

ExecuteOrDelayUntilScriptLoaded(function () {

debugger;

CUI.Ribbon.prototype.$1q_0_old = CUI.Ribbon.prototype.$1q_0;

CUI.Ribbon.prototype.$1q_0 = function () {

this.$1q_0_old();

$(document).trigger('ribbontabselected', [this.get_selectedTabCommand()]);

};

}, 'cui.js');

// Fires 'ribbontabselected' after the ribbon has been initialized after load

ExecuteOrDelayUntilScriptLoaded(function () {

debugger;

var pm = SP.Ribbon.PageManager.get_instance();

pm.add_ribbonInited(function () {

$(document).trigger('ribbontabselected', [SP.Ribbon.PageManager.get_instance().get_ribbon().get_selectedTabCommand()]);

});

}, 'sp.ribbon.js');

// Example code for binding to the event

$(document).on('ribbontabselected', function (e, selectedTabCommand) {

debugger;

if (selectedTabCommand != "ReadTab") {

alert(selectedTabCommand);

}

});