Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ Use the `intersect-full` utility to trigger the event when when the element is f
<div class="intersect:animate-spin intersect-full"></div>
```

### Custom threshold
If `intersect-half` or `intersect-full` don't fit your needs, you can set a custom threshold using Tailwind's arbitrary value syntax: `intersect-[<value>]`, where `<value>` is a number between `0` and `1`.
```html
<div class="intersect:animate-spin intersect-[0.3]"></div>
```
This triggers the event once 30% of the element is visible. Values outside the `0`–`1` range are clamped.

## Custom classes
If you want to define the intersection behavior in a custom class (e.g. with the @apply directive), add a `intersect` class to your HTML element.
```html
Expand Down
26 changes: 20 additions & 6 deletions src/observer/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
const NAMED_THRESHOLDS = {
'intersect-full': 0.99,
'intersect-half': 0.5,
}

const ARBITRARY_REGEX = /(?:^|\s)intersect-\[([\d.]+)\]/

const Observer = {
start() {
if (document.readyState === 'loading') {
Expand Down Expand Up @@ -50,15 +57,22 @@ const Observer = {
})
},

/**
*
* @param {Element} element
* @returns {number}
*/
_getThreshold(element) {
if (element.classList.contains('intersect-full')) {
return 0.99
for (const className in NAMED_THRESHOLDS) {
if (element.classList.contains(className))
return NAMED_THRESHOLDS[className]
}

if (element.classList.contains('intersect-half')) {
return 0.5
const match = element.className.match(ARBITRARY_REGEX)
if (match) {
const threshold = parseFloat(match[1])
if (!Number.isNaN(threshold))
return Math.min(Math.max(0, threshold), 1)
}

return 0
},

Expand Down