Svelte actions, not to be confused with Sveltekit's form actions, are an extremely powerful API for svelte. At their core, actions are functions that allow you to interact directly with the DOM elements by acting as pure JavaScript functions. This makes them perfect for integrating with third-party libraries. One use cases of mine is parallax effects on an image. I wil cover how I achieve this using actions. Link to the repository can be found here.
Installing a third party library
For most cases, any plain js library should work out of the box. I will be using ukiyo-js to handle parallax effect. But you can use any other library of your liking.
Making the action
To start using the library, we need to create our action. Typically, in a Sveltekit project you would put put inside the lib
directory.
I will be creating a file named ukiyo.ts
and then follow the usage within the library readme.md
.
What we need to take notice, is that actions takes as the first parameter a node aka the HTMLElement that we want to have our action. Then the third party library targets that DOM element within its constructor but it can vary depending on the library. We can easily pass options and other arguments that we might need.
If you have noticed, we also need to handle the cleanup. To do so, we return a destroy function from our action. Again, by reading about our third party library, we see that there is a cleanup method, in this case destroy()
. And that is it for creating our action.
Using our action
We have pretty much done all that was needed, now we just put in into action. In any svelte file we import our action and then add the use
plus our action to any component.
And that's it. We can import it pretty much anywhere and use it freely.