Detect when an element is becoming visible or hidden on the page.
Clone or download
Pull request Compare This branch is 1 commit ahead, 40 commits behind Akryum:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
config
dist
src
.babelrc
.eslintignore
.eslintrc.js
.gitignore
README.md
index.js
package-lock.json
package.json
test.html

README.md

vue-observe-visibility

npm npm vue2

Detect when an element is becoming visible or hidden on the page.

Demo

Table of contents

Installation

npm install --save vue-observe-visibility

⚠️ This plugin uses the Intersection Observer API that is not currently supported in every browser (Chrome does though). You need to include a polyfill to make it work on the incompatible browsers.

Default import

import Vue from 'vue'
import VueObserveVisibility from 'vue-observe-visibility'

Vue.use(VueObserveVisibility)

Or:

import Vue from 'vue'
import { ObserveVisibility } from 'vue-observe-visibility'

Vue.directive('observe-visibility', ObserveVisibility)

Distribution import

import VueObserveVisibility from 'vue-observe-visibility/dist/vue-observe-visibility'

Vue.use(VueObserveVisibility)

Or:

import { ObserveVisibility } from 'vue-observe-visibility/dist/vue-observe-visibility'

Vue.directive('observe-visibility', ObserveVisibility)

Browser

<script src="vue.js"></script>
<script src="vue-observe-visibility/dist/vue-observe-visibility.js"></script>

The plugin should be auto-installed. If not, you can install it manually with the instructions below.

Install all the directives:

Vue.use(VueObserveVisibility)

Use specific directives:

Vue.directive('observe-visibility', VueObserveVisibility.ObserveVisibility)

Source import

Install all the directives:

import Vue from 'vue'
import VueObserveVisibility from 'vue-observe-visibility/src'

Vue.use(VueObserveVisibility)

Use specific directives:

import Vue from 'vue'
import { ObserveVisibility } from 'vue-observe-visibility/src'

Vue.directive('observe-visibility', ObserveVisibility)

Usage

The v-observe-visibility directive is very easy to use: just pass a function as the value, which 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.

Example

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

<script>
new Vue({
  el: '#app',
  data: {
    show: true,
    isVisible: true
  },
  methods: {
    visibilityChanged: function (isVisible, entry) {
      this.isVisible = isVisible
      console.log(entry)
    }
  }
})
</script>

License

MIT