-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathstickyheader.jquery.js
More file actions
85 lines (70 loc) · 2.94 KB
/
Copy pathstickyheader.jquery.js
File metadata and controls
85 lines (70 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const STICK_HEADER = {
run: function () {
var $tables = $('table.stickyHeader');
$tables.each(function (i) {
var table = $tables[i];
var bodyHeight, cutoffTop, cutoffBottom, tableHeight, tableWidth;
var tableClone = $(table).clone(true).empty().removeClass('stickyHeader');
var theadClone = $(table).find('thead').clone(true);
var stickyHeader = $('<div></div>').addClass('stickyHeader hide').attr('aria-hidden', 'true');
stickyHeader.append(tableClone).find('table').append(theadClone);
$(table).after(stickyHeader);
var headerCells = $(table).find('thead th');
var headerCellHeight = $(headerCells[0]).height();
var noFixedSupport = (stickyHeader.css('position') === 'absolute');
var stickyHeaderCells = stickyHeader.find('th');
function evaluateHeaderPositionAndSize() {
bodyHeight = $('body').height()
tableHeight = $(table).height();
tableWidth = $(table).width() +
Number($(table).css('padding-left').replace(/px/ig,"")) +
Number($(table).css('padding-right').replace(/px/ig,"")) +
Number($(table).css('border-left-width').replace(/px/ig,"")) +
Number($(table).css('border-right-width').replace(/px/ig,""));
cutoffTop = $(table).offset().top;
cutoffBottom = tableHeight + cutoffTop - headerCellHeight;
for (var i = 0, l = headerCells.length; i < l; i++) {
if (headerCells[i].style.width.length > 0) {
// This takes into account other scripts that set header width
// such as DataTables
stickyHeaderCells[i].style.width = headerCells[i].style.width
} else {
stickyHeaderCells[i].style.width = headerCells[i].scrollWidth + 'px'
}
}
stickyHeader.css('width', tableWidth);
}
function setClassNames() {
for (var i = 0; i < stickyHeader.find('th').length; i++) {
stickyHeader.find('th')[i].className = $(table).find('thead th')[i].className
}
}
evaluateHeaderPositionAndSize()
window.onresize = function () {
evaluateHeaderPositionAndSize()
}
// Sometimes header class names change when clicked
// such as with dataTables sorting
$(table).find('th').click(setClassNames)
stickyHeader.find('th').click(setClassNames)
$(window).scroll(function() {
if (bodyHeight !== $('body').height()) {
evaluateHeaderPositionAndSize()
}
var currentPosition = $(window).scrollTop();
if (currentPosition > cutoffTop && currentPosition < cutoffBottom) {
stickyHeader.removeClass('hide');
if (noFixedSupport) {
stickyHeader.css('top', currentPosition + 'px');
}
}
else {
stickyHeader.addClass('hide');
}
});
});
}
}
jQuery(document).ready(function ($) {
STICK_HEADER.run()
});