56 lines
1.2 KiB
JavaScript
56 lines
1.2 KiB
JavaScript
var React = require('react');
|
|
|
|
module.exports = {
|
|
|
|
isInViewport: function() {
|
|
|
|
var el = React.findDOMNode(this);
|
|
|
|
if(!el) return false;
|
|
|
|
var rect = el.getBoundingClientRect();
|
|
|
|
return (
|
|
rect.top >= 0 &&
|
|
rect.left >= 0 &&
|
|
rect.bottom <= (global.window.innerHeight || global.document.documentElement.clientHeight) && /*or $(window).height() */
|
|
rect.right <= (global.window.innerWidth || global.document.documentElement.clientWidth) /*or $(window).width() */
|
|
);
|
|
|
|
},
|
|
|
|
componentDidMount: function() {
|
|
|
|
function _onInViewport(){
|
|
if( this.isInViewport() ) {
|
|
this.onInViewport();
|
|
}
|
|
}
|
|
|
|
var el = React.findDOMNode(this);
|
|
|
|
if(typeof this.onInViewport === 'function') {
|
|
el.parentNode.addEventListener('scroll', debounce(_onInViewport.bind(this), 250));
|
|
}
|
|
|
|
_onInViewport.call(this);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
function debounce(func, wait, immediate) {
|
|
var timeout;
|
|
return function() {
|
|
var context = this, args = arguments;
|
|
var later = function() {
|
|
timeout = null;
|
|
if (!immediate) func.apply(context, args);
|
|
};
|
|
var callNow = immediate && !timeout;
|
|
clearTimeout(timeout);
|
|
timeout = setTimeout(later, wait);
|
|
if (callNow) func.apply(context, args);
|
|
};
|
|
}
|