I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500
In this solution fixed header is created dynamically, the content and style is cloned from THEAD
all you need is two lines for example:
var $myfixedHeader = $("#Ttodo").FixedHeader(); //create fixed header
$(window).scroll($myfixedHeader.moveScroll); //bind function to scroll event
My jquery plugin FixedHeader and getStyleObject provided below you can to put in the file .js
// JAVASCRIPT
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
Basic usage:
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
//Floating Header of long table PiotrC
(function ( $ ) {
var tableTop,tableBottom,ClnH;
$.fn.FixedHeader = function(){
tableTop=this.offset().top,
tableBottom=this.outerHeight()+tableTop;
//Add Fixed header
this.after('
');
//Clone Header
ClnH=$("#fixH").html(this.find("thead").clone());
//set style
ClnH.css({'position':'fixed', 'top':'0', 'zIndex':'60', 'display':'none',
'border-collapse': this.css('border-collapse'),
'border-spacing': this.css('border-spacing'),
'margin-left': this.css('margin-left'),
'width': this.css('width')
});
//rewrite style cell of header
$.each(this.find("thead>tr>th"), function(ind,val){
$(ClnH.find('tr>th')[ind]).css($(val).getStyleObject());
});
return ClnH;}
$.fn.moveScroll=function(){
var offset = $(window).scrollTop();
if (offset > tableTop && offsettableBottom){
if(!ClnH.is(':hidden'))ClnH.hide();
}
};
})( jQuery );
var $myfixedHeader = $("#repTb").FixedHeader();
$(window).scroll($myfixedHeader.moveScroll);
/* CSS - important only NOT transparent background */
#repTB{border-collapse: separate;border-spacing: 0;}
#repTb thead,#fixH thead{background: #e0e0e0 linear-gradient(#d8d8d8 0%, #e0e0e0 25%, #e0e0e0 75%, #d8d8d8 100%) repeat scroll 0 0;border:1px solid #CCCCCC;}
#repTb td{border:1px solid black}
example
Col1 Column2 Description
info info info
info info info
info info info
info info info
info info info
info info info
info info info
info info info
info info info
info info info
info info info