Reputation: 3755
I have a huge table containing data in vertical and horizontal directions...
Like this: jsfiddle
I am hoping to make the far left column and the top row fixed in a way that when I am scrolling in both directions, I am able to keep the these two (column and row) in place. But only move the content.
How to achieve this with JS/CSS?
I am guessing a pure css solution won't do it, since there is a two-way scroll.
someclass { position: fixed }
Upvotes: 2
Views: 3331
Reputation: 472
The entire code required to answer your question is too large to include here. Instead, I'll link you to the JSBin which holds the answer, and just include the styling and javascript.
The caveats are:
position: fixed
style attribute, you basically break them out of the table.
div
you can position: fixed
and emulate the current behavior of the column headers.HTML:
<!-- Notice I removed background and border color from table tag -->
<table border="0" width="100%" cellpadding="3" cellspacing="1">
<tr>
<td>Dead Cell</td><!-- this cell is not shown -->
...
CSS:
/* Make white space above table since we broke the column headers out of the table */
table {
margin-top: 51px;
position: relative;
}
table td {
border: 1px solid #FFCC00;
height: 44px;
background-color: #FFFFCC;
}
/* styling for column headers */
table tr:first-child {
position: fixed;
top: 0;
left: 57px;
z-index: 100;
}
/* remove first cell in top left position */
table tr:first-child td:first-child {
display: none;
}
table tr:first-child td,
table tr {
position: relative;
}
table tr:first-child td {
background: orange;
}
table tr td:first-child {
background: orange;
position: fixed;
width: 39px
}
/* Make white space to the left of table since we broke the row headers out of the table */
table tr:nth-child(n+2) td:nth-child(2) {
margin-left: 48px;
display: block;
}
JS:
$(function(){ // When document is loaded and ready
$(window).scroll(function() { // When we scroll in the window
// Move column headers into place
$('table tr:first-child td').css('left', - $(this).scrollLeft());
// Move row headers into place
$('table tr td:first-child').each(function() {
$(this).position({ // jQuery UI overloaded function
my: "left top",
at: "left top",
of: $(this).parent(),
using: function(pos) {
$(this).css('top', pos.top);
}
});
});
});
});
Again, here is the link to the JSBin.
Upvotes: 3