- Preview
- Code
PlayPauseButton.js
import { newEvent } from "@/lib/newEvent";
import { pauseCircleSvg, playCircleSvg } from "@/registry/html/icons";
import { BwPlayerConsumer } from "@/registry/html/PlayerProvider";
export class BwPlayPauseButton extends BwPlayerConsumer {
_btn = null;
_listener = null;
constructor() {
super();
this._btn = document.createElement("button");
this._btn.addEventListener("click", () => {
if (!this._player) return;
const name = this._player.playbackState === "playing" ? "Pause" : "Play";
this._player.onEvent(
newEvent({
type: `Pressed${name}`,
description: `The ${name.toLowerCase()} button was pressed.`,
}),
);
});
}
#render() {
const isPlaying = this._player?.playbackState === "playing";
this._btn.setAttribute("aria-label", isPlaying ? "Pause audio" : "Play audio");
this._btn.innerHTML = isPlaying ? pauseCircleSvg(40) : playCircleSvg(40);
}
connectedCallback() {
super.connectedCallback();
this._listener = this._player?.addEventListener("<any>", () => this.#render());
this.#render();
this.appendChild(this._btn);
}
disconnectedCallback() {
this._player?.removeEventListener("<any>", this._listener);
this._listener = null;
super.disconnectedCallback();
}
}
customElements.define("bw-play-pause-button", BwPlayPauseButton);
Installation
npx @beyondwords/cli components add play-pause-button --html
pnpm dlx @beyondwords/cli components add play-pause-button --html
yarn dlx @beyondwords/cli components add play-pause-button --html
bunx --bun @beyondwords/cli components add play-pause-button --html
Usage
Import the modules (each callscustomElements.define), then use the elements. Nest the button inside a <bw-player-provider>.
<bw-player-provider
data-project-id="9504"
data-content-id="ba00ef51-03ac-4a85-8b98-e45c957e8ef8"
data-show-user-interface="false"
>
<bw-play-pause-button></bw-play-pause-button>
</bw-player-provider>
<script type="module">
import "@/registry/html/PlayerProvider";
import "@/registry/html/PlayPauseButton";
</script>
playbackState from the surrounding
<bw-player-provider>. On
click, it emits a PressedPlay / PressedPause event built with
newEvent.
These components expect the BeyondWords player to be available as a global
BeyondWords (the player UMD script). Load it before the provider connects.Reference
| Attributes | None |
| Player state read | playbackState |
| Events emitted | PressedPlay, PressedPause |
| Requires | a <bw-player-provider> ancestor and the player UMD global loaded |