Skip to content

Instantly share code, notes, and snippets.

@wpeasy
Last active April 26, 2024 03:19
Show Gist options
  • Save wpeasy/0338181ec66e9a6746d104c89808f685 to your computer and use it in GitHub Desktop.
Save wpeasy/0338181ec66e9a6746d104c89808f685 to your computer and use it in GitHub Desktop.
Bricks Intersection Observers
(() => {
const animateAttribute = "data-animate";
const partialInSelector = ".animate-in-viewport";
const partialRootMargin = "-20% 0px -20% 0px";
const fullInSelector = ".animate-fully-in-viewport";
// Debounce function to limit the rate of execution
function debounce(func, delay) {
let debounceTimer;
return function () {
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
};
}
document.addEventListener("DOMContentLoaded", () => {
/***************************
* Fully in vuewport observer
*/
// Define the fully observer options
const fullObserverOptions = {
root: null, // observing with respect to the viewport
rootMargin: "0px", // no margin
threshold: 1.0, // 100% of the element needs to be visible
};
// Create the fully in observer
const debounceFullObserver = debounce((entries, observer) => {
entries.forEach((entry) => {
//console.log(entry);
if (entry.isIntersecting) {
// Element is fully within the viewport, add the attribute
entry.target.setAttribute(animateAttribute, "");
} else {
// Element is not fully within the viewport, remove the attribute
entry.target.removeAttribute(animateAttribute);
}
});
}, 100);
const fullObserver = new IntersectionObserver(debounceFullObserver, fullObserverOptions);
// Select all elements with the class and observe them
document.querySelectorAll(fullInSelector).forEach((element) => {
fullObserver.observe(element);
});
/***************************
* Partial in threshold in observer
*/
// Define the fully observer options
const partialObserverOptions = {
root: null, // observing with respect to the viewport
rootMargin: partialRootMargin, //
threshold: 0.01, // Any of the element needs to be visible
};
// Create the fully in observer
const debouncePartialObserver = debounce((
(entries, observer) => {
entries.forEach((entry) => {
//console.log(entry);
if (entry.isIntersecting) {
// Element is fully within the viewport, add the attribute
entry.target.setAttribute(animateAttribute, "");
} else {
// Element is not fully within the viewport, remove the attribute
entry.target.removeAttribute(animateAttribute);
}
});
}
), 100);
const partialObserver = new IntersectionObserver(debouncePartialObserver, partialObserverOptions);
// Select all elements with the class and observe them
document.querySelectorAll(partialInSelector).forEach((element) => {
partialObserver.observe(element);
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment