Add IntersectionObserver to Droplet callout event (#228)

This commit is contained in:
Matt (IPv4) Cowley 2021-02-19 17:55:43 +00:00 committed by GitHub
parent 3d321759e3
commit 4a786d2bfd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -45,10 +45,57 @@ THE SOFTWARE.
components: {
ExternalLink,
},
data() {
return {
observer: null,
};
},
mounted() {
// Use an intersection observer to fire the event when the user scrolls this into view
if ('IntersectionObserver' in window) {
this.observer = new window.IntersectionObserver(this.observerCallback, {
root: null,
rootMargin: '0px',
threshold: 1,
});
this.observer.observe(this.$el);
return;
}
// If we don't have intersection observer support, just fire the visible event now
this.calloutVisibleEvent();
},
updated() {
// If the Vue component updated/re-rendered, ensure we're observing the correct DOM elm
this.$nextTick(() => {
if (this.observer) {
this.observer.disconnect();
this.observer.observe(this.$el);
}
});
},
beforeDestroy() {
// Properly cleanup the observer if the Vue component is being destroyed
this.observerCleanup();
},
methods: {
observerCleanup() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
},
observerCallback(entries) {
for (const entry of entries) {
if (entry.isIntersecting) {
// We've intersected, so we no longer need the observer
this.observerCleanup();
// Fire the event!
this.calloutVisibleEvent();
}
}
},
calloutVisibleEvent() {
analytics({
category: 'Droplet callout',