Adding Sound to Your Website with Alpine.js

I've always believed the web should be a fun place to explore — a place full of surprise and wonder. Too much of the internet has been sterilized, flattened, and neutered. It makes me sad.

If you're reading this article on my website you have probably encountered my sound effects (like hover the nav and clicking my head). If you wonder why, I reply with why not?. Anything you can do to bring character and life back to the web is a good thing in my book.

The "How To" Part

I kept the backstory to 2 short paragraphs. I'll just assume you want to do this since you're here.

I love using Alpine.js and have found it to be one of the simplest ways to add sound effects to my sites, no matter how its built. Here's what you do.

  1. Include Alpine.js
  2. Initialize it globally
  3. Add a ref attribute to an <audio> element
  4. Add an "on" event handler to play() the audio file.
  5. That's it.

Here's a CodePen where you can see it in action.

See the Pen Playing audio with Alpine.js by Jack McDade (@jackmcdade) on CodePen.

You can play sounds on other interactions too.

On Hover

@mouseenter="$refs.mmm.play()"

On Input Focus

@focus="$refs.comeOnIn.play()"

On Pressing Escape

x-on="keydown.escape="$refs.nope.play()"

Go have fun. Make something weird. Make someone laugh.

Published Aug 29, 2020

RSS baby!