Skip to content

v-viewable

The v-viewable directive is for observing the visibility of an element. It uses IntersectionObserver API internally.

The directive bases the visibility on a threshold (default: 1), which is the percentage of the target's visibility at which the callback should be executed. A value of 0 means at least one pixel needs to be visible. A value of 1 means 100% visible.

Import

ts
import vViewable from '@leaflink/stash/directives/viewable';

Basic usage

The directive requires you pass a function as the value.

vue
<script>
  const isInViewRef = ref(false);
  const entry = ref();

  function onView(isInView, entry) {
    isInViewRef.value = isInView;
    entry.value = entry;
  }
</script>

<template>
  <div class="tw-mb-0 tw-w-12 tw-h-12 tw-bg-red-500" v-viewable="onView"></div>
</template>

Is FULLY visible?: false

Keep scrolling to see the value change...








The function will be called whenever the visiblity of the element changes.

The first argument is a boolean: true when the element is fully in view on the page, false when it's not.

The second argument is the corresponding IntersectionObserverEntry object.

IntersectionObserver options

You can optionally provide IntersectionObserver options by providing an object as the directive value with the intersection property. The callback function would instead get passed using the callback property.

template
<div v-viewable="{
  callback: onView,
  intersection: {
    root: ...,
    rootMargin: ...,
    threshold: 0.5,
  },
}">

Once

By using the once modifier, you can observe an element only until it's visible. Once visible, the observer will end, and the callback will no longer fire.

jsx
<div v-viewable.once="onView"></div>

Source and credit: https://github.com/Akryum/vue-observe-visibility (no longer maintained)