From 4a786d2bfd1904ee58b77193801085797dd7aa89 Mon Sep 17 00:00:00 2001 From: "Matt (IPv4) Cowley" Date: Fri, 19 Feb 2021 17:55:43 +0000 Subject: [PATCH] Add IntersectionObserver to Droplet callout event (#228) --- .../templates/callouts/droplet.vue | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/nginxconfig/templates/callouts/droplet.vue b/src/nginxconfig/templates/callouts/droplet.vue index 1b37000..8170461 100644 --- a/src/nginxconfig/templates/callouts/droplet.vue +++ b/src/nginxconfig/templates/callouts/droplet.vue @@ -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',