Building a Music Player Card: Why UI State Should Follow the & Element, Not Guess Ahead of It

Build a music player card in HTML/CSS/JS and learn why animation-play-state beats toggling classes so a paused vinyl resumes instead of resetting.
Building a Music Player Card: Why UI State Should Follow the & Element, Not Guess Ahead of It
The naive version of a play button sets a playing variable to true the instant it's clicked, then updates the icon and the spinning vinyl to match. It looks right in every manual test, because a click and a successful play basically always happen together — until they don't. A track finishes on its own. A browser blocks autoplay before the user has interacted with the page. A file 404s. In every one of those cases, the UI already committed to "playing" before the browser confirmed anything, and now the record is spinning over audio that isn't making a sound. The Music Player Card snippet plays real audio through a native <audio> element and fixes this by inverting the order: the UI never assumes — it waits for the audio element's own play , pause , and ended events and updates from those. Here's the finished card, with real sample tracks wired in — press play, let a track run out, and watch it advance on its own: Grab the code, or open the full editor …

About the author

Puneet Sharma is a freelance web developer and the creator of FWD Tools and WebDevPuneet. Follow him on X/Twitter

Post a Comment