Skip to content

Instantly share code, notes, and snippets.

@alchen
Created May 31, 2015 00:24
Show Gist options
  • Save alchen/f552e979830ac73493a2 to your computer and use it in GitHub Desktop.
Save alchen/f552e979830ac73493a2 to your computer and use it in GitHub Desktop.
Vue.js viewport detect
'use strict';
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return rect.bottom > 0
&& rect.right > 0
&& rect.top < (window.innerHeight || document.documentElement.clientHeight)
&& rect.left < (window.innerWidth || document.documentElement.clientWidth);
}
var directives = [];
function notify (directive) {
if (!directive.el) return;
var inViewport = isElementInViewport(directive.el);
if (directive.inViewport === null || directive.inViewport !== inViewport) {
directive.inViewport = inViewport;
var direction = inViewport ? 'enter' : 'leave';
directive.vm.$emit('viewport' + direction, directive.el);
}
}
function notifyAll () {
directives.forEach(notify);
}
var timeThreshold = 300;
window.setInterval(function () {
notifyAll();
}, timeThreshold);
var directive = {
isEmpty: true,
bind: function () {
this.vm.$on('hook:attached', notifyAll);
this.vm.$on('hook:detached', notifyAll);
if (directives.indexOf(this) === -1) {
directives.push(this);
}
},
unbind: function () {
this.vm.$off('hook:attached', notifyAll);
this.vm.$off('hook:detached', notifyAll);
var index = directives.indexOf(this);
if (index > -1) {
directives.splice(index, 1);
}
}
};
module.exports.install = function (Vue, options) {
Vue.directive('detect-viewport', directive)
};
@alexisgahon
Copy link

window.setInterval(function () {
	notifyAll();
}, timeThreshold);

Why not watch the scroll event ?
No need to check if it's in the viewport if the viewport didn't changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment