Vue 2.x directive using Intersection Observer API that detects if the element is visible (in the viewport and not hidden by CSS).


npm install --save vue-observe-visibility

This also works on components:

<MyComponent v-observe-visibility="visibilityChanged" />

The function will be called whenever the visiblity of the element changes with the argument being a boolean (true means the element is visible on the page, false means that it is not).

The second argument is the corresponding IntersectionObserverEntry object.

visibilityChanged (isVisible, entry) {
  this.isVisible = isVisible

Passing custom arguments

You can add custom argument by using an intermediate function:

<div v-observe-visibility="(isVisible, entry) => visibilityChanged(isVisible, entry, customArgument)">

Here visibilityChanged will be call with a third custom argument customArgument.


<div id="app">
  <button @click="show = !show">Toggle</button>
    <input type="checkbox" v-model="isVisible" disabled/> Is visible?
  <div ref="test" v-show="show" v-observe-visibility="visibilityChanged">Hello world!</div>

new Vue({
  el: '#app',
  data: {
    show: true,
    isVisible: true,
  methods: {
    visibilityChanged (isVisible, entry) {
      this.isVisible = isVisible