Styling audio
and video
elements can be a bit of a pain, especially across browsers. At the same time current solutions are either hacky CSS or overly engineered JavaScript. The play-button
component allows you to play, and pause, audio and video with a single button
element.
play-button
<play-button>
connects <audio>
and <video>
elements up to a single <button>
element so that you can control the playing and pausing of the audio or video.
The component came out of my need to style the audio
element, which found me fighting a lot with browser specific styles that ultimately would need to be done again in the next browser I tested in. In addition the options out there are far too large for my needs, as I just wanted to play a small piece of audio without all the controls taking up space on screen.
Usage
The <play-button>
component can be used with the help of a script tag and placing a typical form within it like so:
Note that the content of the Web Component is just an audio
element and a button
element, and this is what will be rendered on the page. To hide the audio
element you can make use of the :defined
pseudo selector, ensuring to maintain a graceful fallback if the component doesn't load properly:
The above example utilises play-button:defined
to hide the audio
when the component is loaded and play-button:not(:defined)
to hide the button
if the component hasn't loaded.
Usage with other Web Components
One additional feature of play-button
is that pressing the button while the audio or video is playing will pause it. If you want to change how the button looks to reflect state you can use it in conjunction with the is-playing
Web Component I created:
The above example utilises is-playing[playing]
to hide the play label when the audio is playing and is-playing:not([playing])
to hide the pause label when the audio is not playing.
See my article about the is-playing
Web Component for more details:
Further reading
You can check out the source code, documentation and working demo over on GitHub: