Less Or No JavaScript with Invokers
How to add behavior to buttons with just HTML
Feb 5, 2024
Invokers enable developers to assign behavior to buttons in a more declarative and accessible way. In plain English: less JavaScript and less bugs!
The basic idea is that you add an invoketarget attribute to a <button> that holds the id of the element that is the target of the invoked action:
<button invoketarget="my-popover">Open Popover</button>
<div id="my-popover" popover="auto">This is a popover</div>
In this example, when the button is clicked it will open the popover. This is the default behavior of the invoker (the button) which is equivalent to setting the invokeaction attribute to auto.
Invokers are currently implemented in Chrome Canary with Experimental Web Features enabled and in Firefox Nightly with dom.element.invokers.enabled in about:config. Default behavior is implemented in Chrome Canary when the target is a popover, as shown in the previous example, and when the target is a <details> element in both Chrome Canary and Firefox Nightly:
<button invoketarget="my-details">Open Details</button>
<details id="my-details">
<summary>Summary...</summary>
Hello world!
</details>
You can also specify a predefined behavior in invokeaction, for example showPicker to open the file picker that is displayed when you click a file input:
<button invoketarget="my-file" invokeaction="showPicker">
Pick a file
</button>
<input id="my-file" type="file">
This will open the file picker in Chrome Canary.
Custom behavior with invokers
Where invokers really shine is when you implement custom behavior. When a button with invoketarget is clicked it dispatches an InvokeEvent on the target that has an action property that holds the value of the invokeaction attribute of the button. This way, you can implement two buttons that show and hide a <dialog> respectively:
<button invoketarget="my-dialog" invokeaction="show">
Open dialog with custom behavior
</button>
<button invoketarget="my-dialog" invokeaction="close">
Close dialog with custom behavior
</button>
<dialog id="my-dialog">This is the dialog</dialog>
<script>
const dialog = document.querySelector('#my-dialog');
dialog.addEventListener('invoke', ({action}) => {
if(action === 'show') {
dialog.show();
}
if(action === 'close') {
dialog.close();
}
});
</script>
The beauty of this is that the event is invoked on the target instead of the buttons. This way, you can make as many buttons as you want invoke an action with a single event handler. A simple but brilliant paradigm shift.
How about event bubbling?
Of course, you could also rely on event bubbling to reduce the amount of event handlers. If you have 5 buttons you could also wrap them in a <div>, set the event handler on that instead of each button, and then figure out which button was clicked in the event handler.
That would also work, but there is another nice feature of invokers, let me explain.
I write a lot of vanilla Web Components and a pattern that keeps emerging is that I have to select an element inside the component’s shadow root and attach an event handler to it.
Here’s an example that you can find on my Github page, audio-recorder. It’s a Web Component that can capture audio through the user’s microphone, record it, and then show a waveform or a frequency analyzer when the recorded audio is played. You can toggle between the waveform and frequency analyzer view and there are buttons to save the audio or adjust the volume.
A significant part of the code is selecting the buttons inside the shadow root and attaching event handlers to them to perform all the actions like record, play, save, and toggle the view:
this.playButton = this.shadowRoot.querySelector('#play');
this.pauseButton = this.shadowRoot.querySelector('#pause');
this.captureAudioButton = this.shadowRoot.querySelector('#capture-audio');
// more buttons
this.playButton.addEventListener('click', this.playPause.bind(this));
this.pauseButton.addEventListener('click', this.playPause.bind(this));
this.captureAudioButton.addEventListener('click', this.captureAudio.bind(this));
// more event handlers
When using invokers, we can replace all these event handlers with a single one. Let’s start by adding invoketarget and invokeaction attributes to the buttons (check the source on Github for the original buttons in the master branch and the buttons with invokers in the feat/invokers branch):
<button
id="capture-audio"
invoketarget="container"
invokeaction="capture">
<i class="material-icons">mic</i>
</button>
<button
id="play"
invoketarget="container"
invokeaction="play">
<i class="material-icons">play_arrow</i>
</button>
<button
id="pause"
invoketarget="container"
invokeaction="pause">
<i class="material-icons">pause</i>
</button>
These are not all the buttons inside the component because I edited it for clarity but I assume you get the idea. Each button has an invoketarget that is container. This is the top-level <div> inside the audio-recorder component that has id="container". All actions will be invoked on this <div> so we can set the single event handler for the invoke event on this element.
When a button is clicked, we check its invokeaction inside the invoke event handler and then call the method of the component that would normally be called inside the click event handler of that button. For example, when <button id="play"> is clicked, this.playPause() will be called.
All we then need to do is connect all invokeactions to the right method. Note that we will not set the invoke event handler on <div id="container"> but on this, which is the audio-recorder component itself. I'll explain why in a minute:
this.addEventListener('invoke', ({action}) => {
const actions = {
'capture': this.captureAudio,
'stop-capture': this.stopCaptureAudio,
'play': this.playPause,
'pause': this.playPause,
'record': this.recordAudio
...
}
if(actions[action]) {
actions[action].call(this);
}
});
Instead of an event handler for each button, we now have one simple event handler that takes care of all actions that the buttons can invoke.
So why is the event handler set on this and not <div id="container"> which is the invoketarget of each button?
Imagine we want to allow users to provide their own buttons to control the audio-recorder component. We could do this by requiring users to provide those buttons as slotted content or have users add event handlers to their buttons to invoke the correct methods of the component:
// as slotted content
<audio-recorder>
<button id="play" slot="play-button">Play</button>
<button id="record" slot="record-button">Record</button>
...
</audio-recorder>
// with event handlers
const audioRecorder = document.querySelector('audio-recorder');
const playButton = document.querySelector('#play');
playButton.addEventListener('click', () => audioRecorder.playPause());
But by setting the invoke event handler on the audio-recorder itself we can now also create buttons outside of it to invoke the same actions the buttons inside of it do. Basically, we can define the same buttons on the outside, we only need to change the invoketarget to the audio-recorder itself by setting and id on it and using that as the valu of invoketarget:
<audio-recorder id="recorder"></audio-recorder>
<button id="play" invoketarget="recorder" invokeaction="play">
Play
</button>
<button id="pause" invoketarget="recorder" invokeaction="pause">
Pause
</button>
Your component can communicate which actions are available and the consumers of your component can use their own buttons with simple, declarative HTML and zero JavaScript.
Invokers is currently a proposal from Open UI, a W3C Community group whose purpose is to allow web developers to style and extend built-in web UI components and controls and was written by Keith Cirkel (@Keithamus)
Currently, invokers are supported in Chrome, Edge, Safari Tech Preview 185 and Firefox Nightly, which means that we’ll probably have universal support soon!
Check out the Invokers explainer that lists all the details and Keith’s counter demo.