files/en-us/web/api/invoker_commands_api/index.md
{{DefaultAPISidebar("Invoker Commands API")}}
The Invoker Commands API provides a way to declaratively assign behaviors to buttons, allowing control of interactive elements when the button is enacted (clicked or invoked via a keypress, such as the spacebar or return key).
A common pattern on the web is to have {{HTMLElement("button")}} elements control various aspects of the page, such as opening and closing {{domxref("Popover API", "popovers", "", "nocode")}} or {{HTMLElement("dialog")}} elements, formatting text, and more.
Historically creating these kinds of controls has required JavaScript event listeners added to the button which can then call the APIs on the element they control. The {{domxref("HTMLButtonElement.commandForElement", "commandForElement")}} and {{domxref("HTMLButtonElement.command", "command")}} properties provide a way to do this declaratively for a limited set of actions. This can be advantageous for built-in commands as the user does not have to wait for JavaScript to download and execute to make these buttons interactive.
commandfor
command
<button>, specified via the commandfor attribute.commandfor HTML attribute.command HTML attribute.<button commandfor="mypopover" command="toggle-popover">
Toggle the popover
</button>
<div id="mypopover" popover>
<button commandfor="mypopover" command="hide-popover">Close</button>
Popover content
</div>
<button commandfor="mydialog" command="show-modal">Show modal dialog</button>
<dialog id="mydialog">
<button commandfor="mydialog" command="close">Close</button>
Dialog Content
</dialog>
<button commandfor="my-img" command="--rotate-left">Rotate left</button>
<button commandfor="my-img" command="--rotate-right">Rotate right</button>
const myImg = document.getElementById("my-img");
myImg.addEventListener("command", (event) => {
if (event.command === "--rotate-left") {
myImg.style.rotate = "-90deg";
} else if (event.command === "--rotate-right") {
myImg.style.rotate = "90deg";
}
});
{{Specifications}}
{{Compat}}