Reputation: 1841
I have a fixed header scrolling table with horizontal and vertical scroll bars, for which I can presently sort on each column but am unable to properly preserve horizontal position of the table when loading the page.
Using the following inline css I get scrollAmount
from php from a hidden input whose value is from a jquery code and input it into the inline css
style="transform:translateX(<negative offset value of scrollAmount>)"
My question is how do I properly maintain scroll position for a table that overflows with a horizontal scroll bar using CSS and jQuery without waiting for the page to completely load / finish rendering?
Inline style
transform:translateX(-<?=scrollAmount()?>px)
jQuery Scroll Position Function
function setScroll(id_header, id_table)
{
$('div.'+id_table).on("scroll", function(){ //activate when #center scrolls
var left = $('div.'+ id_table).scrollLeft(); //save #center position to var left
$('div.'+id_header).scrollLeft(left); //set #top to var left
$('#scrollamount').val(left);
});
Hidden Input HTML Code
<input type="hidden" id="scrollamount" name="scrollamount" value=<?=scrollAmount()?>"/>
PHP Code
function scrollAmount()
{
if (isset($_POST['scrollamount']))
return $_POST['scrollamount'];
return "";
}
Upvotes: 0
Views: 1115
Reputation: 1841
Using the following code, I was able to produce a visually acceptable solution that keeps the table horizontally offset by the user's scrolled amount.
JS Code - Executes on document.ready() when table has finished fetching/loading
//Translate 0px, undoing the original translation
$('table#'+ id_table).attr("style", "transform:translateX(0px)");
$('table#'+ id_header).attr("style", "transform:translateX(0px)");
//Scroll left to the desired amount as defined in the hidden input `#scrollamount`
$('div.'+ id_table).scrollLeft($('#scrollamount').val());
$('div.'+ id_header).scrollLeft($('#scrollamount').val());
HTML / PHP Code - Fixed Header Scrolling Table (Header and Table Body)
<div class="summary_header">
<table id="summary_header" border=1 style="transform:translateX(-<?=scrollAmount()?>px)">
... <-----Table Header Definition
</table>
</div>
<div class="summary_table" style="overflow-x:scroll">
<table id="summary_table" style="transform:translateX(-<?=scrollAmount()?>px)">
... <--Table Body Definition
</table>
</div>
Upvotes: 0
Reputation: 621
The problem is that .scrollLeft()
will change every time you scroll, so you're simply setting it to where it's scrolled to. You could probably find the position of the table with jQuery, set that to a universal variable at the start, and then later use $('div.'+id_header).scrollLeft(globalLeftPosition)
to set it. Hope this helps.
Upvotes: 1