Thursday, September 30, 2010

Animated scroll Ext JS grid row into view

I've been using Ext JS at work for a week or so now, mainly for the
grids. Everything went well until I wanted to scroll a grid row into

Googling found responses like this one:

The problem with focusRow is that the grid just jumps to the new row
with no animation. I also wanted the focused row to be centered in the
grid, but focusRow prefers to put the row at the bottom of the grid.

Happily, there's an easy answer. A little digging through the Ext JS
source and you can hack up an animated scroll to bring a grid row to
the center of the grid as:

function smoothScrollIntoView(element, container) {
var c = Ext.getDom(container) || Ext.getBody().dom,
el = element.dom,
o = element.getOffsetsTo(c),
t = o[1] + c.scrollTop,
ch = c.clientHeight;
var newCTop = t - ch / 2;
if (newCTop < 0)
newCTop = 0;
container.scrollTo('top', newCTop, true);

function gridRevealRow(grid, rowIndex) {
var row = new Ext.Element(grid.getView().getRow(rowIndex));
smoothScrollIntoView(row, grid.getView().scroller);

And then you can just call gridRevealRow(grid, rowindex) to scroll
a grid row into view.