Skip to content

Instantly share code, notes, and snippets.

@briedis
Created February 27, 2017 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briedis/ca8916a7c0ee93443034134634e285db to your computer and use it in GitHub Desktop.
Save briedis/ca8916a7c0ee93443034134634e285db to your computer and use it in GitHub Desktop.
/**
*
* @param {T.LoadMore.Par} par
* @constructor
*/
T.LoadMore = function(par){
this.nextPageUrl = par.nextPageUrl;
this.node = par.node;
this.id = this.node.id;
this.autoLoads = par.autoLoads || 3;
this.node.removeAttribute('id'); // Avoiding duplicate id's in the next page load
this.scrollEventName = 'scroll.' + this.id;
// Initialize / store globally out load count
T.LoadMore.loadCounts[this.id] = T.LoadMore.loadCounts[this.id] || 0;
this.button = mkE({
tag : 'a',
className : 'btn btn-primary btn-lg',
href : this.nextPageUrl,
prop : {
onclick : T.closure(this, this.onClick)
},
text : 'Ielādēt vairāk'
})
addClassName(this.node, 'text-center');
this.button.append(this.node);
$(window).on(this.scrollEventName, T.closure(this, this.onScroll));
};
T.LoadMore.prototype.onScroll = function(){
if(!this.canAutoLoad()){
return;
}
var
$node = $(this.node),
docViewTop = $(window).scrollTop(),
docViewBottom = docViewTop + $(window).height(),
elemTop = $node.offset().top,
elemBottom = elemTop + $node.height(),
isElementVisible = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
if(isElementVisible){
this.registerAutoLoad();
this.loadNext();
}
};
T.LoadMore.prototype.onClick = function(event){
event.preventDefault();
this.resetAutoLoads();
this.loadNext();
};
/**
* Load next page
*/
T.LoadMore.prototype.loadNext = function(){
$(window).off(this.scrollEventName);
addClassName(this.button, 'disabled');
$.get(this.nextPageUrl, T.closure(this, this.loaded));
};
T.LoadMore.prototype.loaded = function(data){
$(data).insertAfter(this.node);
removeNode(this.node);
};
T.LoadMore.prototype.canAutoLoad = function(){
var count = T.LoadMore.loadCounts[this.id] || 0;
return count < this.autoLoads;
}
T.LoadMore.prototype.registerAutoLoad = function(){
T.LoadMore.loadCounts[this.id] = (T.LoadMore.loadCounts[this.id] || 0) + 1;
};
T.LoadMore.prototype.resetAutoLoads = function(){
T.LoadMore.loadCounts[this.id] = 0;
}
/**
* Continuous load count for item
* @type {{Number}}
*/
T.LoadMore.loadCounts = {};
T.LoadMore.Par = function(){
}
/**
* @type {Node}
*/
T.LoadMore.Par.prototype.node = null;
T.LoadMore.Par.prototype.nextPageUrl = '';
/**
* How much times should it load automatically on scroll
* @type {number}
*/
T.LoadMore.Par.prototype.autoLoads = 4;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment