https://github.com/markmead/alpinejs-sticky
Toggle CSS class names when an element becomes sticky to the DOM 🐙
https://github.com/markmead/alpinejs-sticky
alpine-js alpinejs alpinejs-plugin javascript sticky sticky-elements
Last synced: 12 months ago
JSON representation
Toggle CSS class names when an element becomes sticky to the DOM 🐙
- Host: GitHub
- URL: https://github.com/markmead/alpinejs-sticky
- Owner: markmead
- License: mit
- Created: 2022-02-12T10:13:47.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2025-03-11T13:25:37.000Z (over 1 year ago)
- Last Synced: 2025-04-04T02:11:17.441Z (about 1 year ago)
- Topics: alpine-js, alpinejs, alpinejs-plugin, javascript, sticky, sticky-elements
- Language: JavaScript
- Homepage: https://js.hyperui.dev/examples/utility-update-class-when-sticky
- Size: 28.3 KB
- Stars: 33
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Alpine JS Sticky
Toggle CSS class names when an element becomes sticky to the DOM 🐙
## Install
### With a CDN
```html
```
### With a Package Manager
```shell
npm i -D alpinejs-sticky
yarn add -D alpinejs-sticky
```
```js
import Alpine from 'alpinejs'
import sticky from 'alpinejs-sticky'
Alpine.plugin(sticky)
Alpine.start()
```
## Example
```html
Hello World!
Hello World!
```
`x-sticky="!bg-red-500"`
This will add `!bg-red-500` to the element when it is sticky to the DOM.
`x-sticky.sticky-root="!block"`
This will add `!block` to the element when the `sticky-root` element is sticky
to the DOM.
At times you might need to apply the `! important` modifier to your CSS.
_This example uses Tailwind CSS classes, but any CSS class names will work._
## Modifiers
As shown you can pass a class name as a modifier to target a specific HTML
element.
You can also pass `wait` which will use the `scroll` event listener instead of
the `IntersectionObserver`. Why would you want this? Well, it comes in handy
when the element is already at the top of the DOM and you don't want the stuck
classes applying.
## Options
**`x-sticky-inactive`**
This allows you to pass classes that apply to the element when it's not stuck.
These will be toggled alongside the active classes.
Using this means you do not need an `! important` modifier with your CSS.
**`x-sticky-root`**
By default this is `-1px 0px 0px 0px`.
[MDN IntersectionObserver API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
I have removed the `x-sticky-threshold` option as I found it unnecessary through
my uses.
### Stats



