In order to react to a toggle button change, add an event listener to the ribbonTabsLoaded event and identify the id of the desired ribbon element for example by using the browser developer tool.
MutationObserver
A MutationObserver will allow you to react to changes in the DOM element. Switch statements can be used to distinguish between different cases.
It is important to use the correct observer configuration. Make sure to observe changes in the whole sub tree and also to pass the right root element as a target node in the MutationObserver.observe() method.
This code snippet shows how to detect toggles of the Bullet List dropdown in the ribbon Home tab. Therefore, the Paragraph group is passed as root element.
window.addEventListener("load", () => { | |
TXTextControl.addEventListener("ribbonTabsLoaded", () => { | |
// Obtain "Paragraph" ribbon group element (get further ribbon group element ids | |
// by using the browser developer tools) | |
const ribbonGroupParagraph = document.getElementById("ribbonGroupParagraph"); | |
const observer = new MutationObserver(mutations => { | |
for (mutation of mutations) { | |
switch (mutation.type) { | |
case "attributes": | |
switch (mutation.attributeName) { | |
case "class": | |
// The "class" attribute of an element has been changed. | |
// Get the affected element and figure out which button | |
// was pressed via the element id. | |
const button = mutation.target; | |
switch (button.id) { | |
case "ribbonTabHome_drpDnBtnBulletList": | |
// "Bulleted list" button. | |
// The "toggled" state can be determined via the CSS class | |
// "ribbon-button-selected". | |
if (button.classList.contains("ribbon-button-selected")) { | |
console.info("'Bulleted list' button toggled.") | |
} | |
else { | |
console.info("'Bulleted list' button un-toggled.") | |
} | |
break; | |
case "ribbonTabHome_drpDnBtnNumberedList": | |
// "Numbered list" button. | |
// ... | |
break; | |
// Get further button ids by browsing the html structure | |
// using the browser developer tools. | |
} | |
break; | |
} | |
break; | |
} | |
} | |
}); | |
// Observer configuration (We want to observe changes in the whole sub-tree of the | |
// "Paragraph" group root element). | |
const config = { attributes: true, subtree: true }; | |
// Pass in the target node (in this case the "Paragraph" group root element) and | |
// the observer options. | |
observer.observe(ribbonGroupParagraph, config); | |
}); | |
}); |