Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial commit of useIntersectionObserver composable. #70

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
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
63 changes: 63 additions & 0 deletions resources/js/components/UseIntersectionObserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* @function useIntersectionObserver
* @param {HTMLElement} elementToWatch elementToWatch
* @param {function} callback callback once element is intersecting
* @param {function} outCallback callback once element is not intersecting (optional)
* @param {Boolen} once if callback only run one time
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boolean

* @param {Object} options Intersection Observer API options
* @return {Object}
*/
import {
ref,
onMounted,
onUnmounted
} from 'vue'

export function useIntersectionObserver (
elementToWatch,
callback,
config = {
outCallback: () => {},
once: true,
options: {
threshold: 0.1,
},
}
) {
const isIntersecting = ref(false)

const { outCallback, once, options } = config

// Initiate the observer
const observer = new IntersectionObserver(([entry]) => {
// If the element to watch is intersecting within the threshold
if (entry && entry.isIntersecting) {
// Update the reactive isIntersection
isIntersecting.value = true

// Run the callback
callback(entry.target)

// If the callback should only run once, unobserve the element
if (once) {
observer.unobserve(entry.target)
}
} else {
// Update the reactive isIntersection
isIntersecting.value = false

// Run the callback
outCallback(entry.target)
}
}, options)

// Observe/unobserve within lifecycle hooks
onMounted(() => observer.observe(elementToWatch))
onUnmounted(() => observer.disconnect())

// Returns reactive version of isIntersecting, and the observer itself
return {
isIntersecting,
observer,
}
};