I have a table of many rows in a JQuery UI accordion.
I dynamically append the table this way:
var resJson = JSON.parse(connector.process(JSON.stringify(reqJson)));
for ( var i in resJson.entryArrayM) {
// test if entry has already been displayed
if ($("#resultTr_" + resJson.entryArrayM[i].id) == null)
continue;
$("#resultTable > tbody:last").append(listEntry.buildEntryRow(resJson.entryArrayM[i]));
}
Firstly I check if a row of the same tr id already exists. If not, I would append to the last row of the table.
It works. But the problem is: every time a row is appended, the accordion would scroll to the first row of the table. Since the table is remarkably long, it makes users inconvenient to scroll down again and again to watch newly-added rows. So how to avoid this?
First of all, just do one
appendrather than appending every time through the loop:Also note that I corrected your existence test,
$(x)returns an empty object whenxdoesn’t match anything, notnull. Not only is this a lot more efficient but you’ll only have one scroll position change to deal with.Solving your scrolling issue is fairly simple: find out what element is scrolling, store its
scrollTopbefore your append, and reset itsscrollTopafter the append:There might be a slight visible flicker but hopefully that will be lost in the noise of altering the table.
You could also try setting the
table-layoutCSS property of the<table>tofixed. That will keep the table from trying to resize its width or the width of its columns and that might stop the scrolling behavior that you’re seeing. The downside is that you’ll have to handle the column sizing yourself. But, you could try settingtable-layout:fixedimmediately before yourappendoperation to minimize the hassle.