How to use AlpineJS v3 in CodePen

February 9th, 2023 | Adam Johnson

If you're throwing together a quick demo and use AlpineJS v3, you may notice that Codepen doesn't allow you to just slap a “normal” Alpine function in the JS panel. To get it to work, you must add a the alpine:init event listener and call Alpine.start();.

Here’s a demo with instructions:

See the Pen Using Alpine v3 with Codepen by Adam Johnson (@adamjohnson) on CodePen.

Note the following in the JS panel:

document.addEventListener('alpine:init', () => {
  Alpine.data('itWorks', () => ({
    init () {
      console.log('This ran automatically on init');
    }
    // ...more functions can go here...
  }));
});

Alpine.start();

Since Codepen automatically inserts the AlpineJS script tag at the end of the DOM without a defer attribute, we have to specifically wait for alpine:init before we can run any of our custom JavaScript.

Note: Somewhere in your HTML, you need something like:

<div x-data="itWorks">...<div>

You can change itWorks to whatever you like in both your HTML and JavaScript.

Happily, this seems to only be necessary for Codepen and environments where you cannot control where you call the AlpineJS library (use defer!). For all other situations, you can proceed as normal (no event listeners, just plain function‘s.


I’ve recently removed comments from this blog. Want to chime in? See something wrong?
Email me at Email me!. I’d love to hear from you. I read every email and welcome your input.