Skip to content

Instantly share code, notes, and snippets.

@Gitsack
Last active March 10, 2021 20:39
Show Gist options
  • Save Gitsack/112e5aa81c5c726ade62b06f9a987017 to your computer and use it in GitHub Desktop.
Save Gitsack/112e5aa81c5c726ade62b06f9a987017 to your computer and use it in GitHub Desktop.
Vue - in-viewport directive (Intersection Observer)
Vue.directive("in-viewport", {
inserted: function(el, binding) {
if(!!window.IntersectionObserver){
el.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.isIntersecting){
if (typeof binding.value === "function"){
binding.value();
}
entry.target.src = entry.target.dataset.src;
if (binding.modifiers.once){
el.observer.unobserve(entry.target);
}
}
});
}, {threshold: binding.modifiers.full ? 1 : 0});
el.observer.observe(el);
}
},
unbind: function(el){
el.observer.disconnect();
}
});
// USAGE
// <div v-in-viewport="functionNameToCall"></div>
//
// Available modifiers:
// .once - unbind after first function call
// .full - only fire the event if whole element is visible in viewport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment