≪ Today I learned. RSS購読
公開日
タグ
HTML
著者
ダーシノ(@bc_rikko)

Invoker Commands APIのcommand/commandforを使って宣言的に動作を割り当てる

Popover APIのように、インタラクティブ要素と操作対象の要素をHTML属性で紐づけ、操作することができるInvoker Commands APIが、主要ブラウザに実験的に実装されている。

Popover APIの場合は、popover属性とpopovertarget属性、popovertargetaction属性を使って、以下のように要素をひもづけていた。

<button popovertarget="my-dialog">
  Show dialog
</button>

<dialog id="my-dialog" popover>
  <button
       popovertarget="my-dialog"
       popovertargetaction="hide"
    >Close</button>
    Dialog Content
</dialog>

Invoker Commands API

Invoker Commands APIでは、それらの属性の代わりにcommand属性とcommandfor属性を使って、より宣言的にわかりやすい紐づけができるようになる。

<button
  commandfor="my-dialog"
  command="show-modal"
>
  Show dialog
</button>

<dialog id="my-dialog">
    <button
       commandfor="my-dialog"
       command="close"
    >Close</button>
    Dialog Content
</dialog>

commandfor属性で操作する対象を指定し、command属性でどんな操作をするか指定する。

ちなみにcommand属性には以下のようなものが用意されている。

カスタムコマンド

commandにはカスタムコマンドを指定することもできる。

<button
  commandfor="my-img"
  command="--rotate"
>Rotate</button>

<img id="my-img" />
const myImg = document.getElementById('my-img');

myImg.addEventListener('command', (event) => {
  if (event.detail === '--rotate') {
    myImg.style.transform = 'rotate(90deg)';
  }
});