Alpinejs is a tiny Javascript framework that lets us sprikle in different behaviour that you would usually see in big frameworks like Vuejs - but at a much lower cost. Load in the Alpinejs script from a CDN and the full 6.4kb libary is yours.
Controlling videos with Alpinejs
-
Mon Mar, 2021
-
10 views
Alpinejs is a tiny Javascript framework that lets us sprikle in different behaviour that you would usually see in big frameworks like Vuejs - but at a much lower cost. Load in the Alpinejs script from a CDN and the full 6.4kb libary is yours.
Recently I've been building a client website that didn't need a big system on the back end - and the goal is just to host it off Netlify in the end. We could of gone down the road of creating Vue components (as I reallly 💕 Vue!) but decided to give Alpine a try as all I really needed to do is make the page a bit reactive.
Controlling Videos
Videos in HTML5 are simple to get up and running - and come with some AMAZING features. Check out the article on MDN about videos to see what I mean.
Our designer created an idea for a component that had a video on it - the feature list is:
- No controls
- Play icon on the video which disappears when clicked
- When video clicked it'll toggle playing / pausing
Using Alpinejs this was pretty hard to work out. Here is my solution:
You can view a demo here on CodePen
See the Pen Alpine.js controlling a video by jake (@jakeywr) on CodePen.
The magic is done by a couple of cool features of Alpinejs:
x-ref allowing us to reference our video tag inside our component.
x-init allows us to write an expression - in this case we target our video reference ($refs.video
) and start and stop (or pause!) when we toggle the play state.