Last active
March 10, 2021 20:39
-
-
Save Gitsack/112e5aa81c5c726ade62b06f9a987017 to your computer and use it in GitHub Desktop.
Vue - in-viewport directive (Intersection Observer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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