david-d
5/26/2015 - 1:53 PM

Pickup a sticky Element Basic CommonJS Constructor

Pickup a sticky Element Basic CommonJS Constructor

var $         = window.jQuery;

/**
 * A sticky element class
 * @param  {Object}  $el  the dom elemnt
 */
function StickyElement($el) {
	this.self       = $el;
	this.selfTop    = $el.offset().top;
	this.selfHeight = $el.height();
}

/**
 * Function to initialize the sticky behavior.  */
StickyElement.prototype.init = function() {
	var $placeholder = $('<div></div>').addClass('sticky-placeholder');

	var stickyElement = this;

	stickyElement.self.before($placeholder);

	stickyElement.$placeholder = stickyElement.self.prev('.sticky-placeholder');

	$(window).on('scrollStart', function(event, windowTop) {
		if (windowTop > stickyElement.selfTop ) {
			stickyElement.self.attr('data-sticky', 'true');
			stickyElement.$placeholder.height(stickyElement.selfHeight);
		} 
		
		if (windowTop <= stickyElement.selfTop + 1){
			stickyElement.self.attr('data-sticky', 'false');
			stickyElement.$placeholder.height(0);
		}
	});

};

module.exports = StickyElement;