Created
May 31, 2015 00:24
-
-
Save alchen/f552e979830ac73493a2 to your computer and use it in GitHub Desktop.
Vue.js viewport detect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not watch the scroll event ?
No need to check if it's in the viewport if the viewport didn't changed.