tags:

views:

239

answers:

2

I have a page operation that uses something like:

$('#thetable tbody').replaceWith(newtbody);

in an ajax callback. Sometimes, if the user had scrolled the page down, this operation has the understandable side effect of scrolling the page back up. But the replacement appears seamless to the user so it's a bit annoying to have to scroll back down again. And since the newtbody normally has the same vertical height as the one it replaced, we should be able to make the script do it instead.

Now, since I found that executing:

$('body').scrollTop(300);

from the JS debugger console does what I hoped it would, I thought the simple remedy would be:

var scrollsave = $('body').scrollTop();
$('#thetable tbody').replaceWith(newtbody);
$('body').scrollTop(scrollsave);

but no joy. I haven't resorted to jQuery.ScrollTo yet.

+1  A: 

We had the exact same problem, and the following code works great...

var scroll = $(window).scrollTop();
// yada
$("html").scrollTop(scroll);
Josh Stodola
I tried it. Also no luck. Debugging shows that no matter what I use as selector in the first line, be it `window`, `"body"`, `"html"`, etc., the value returned by `scrollTop(...)` is always zero. Odd! Could the context of being in a anonymous callback possibly affect that?
fsb
That's weird. Scroll down on this page. Paste this in your browser address bar and press enter: `javascript:alert($(window).scrollTop());` It works fine for me here on IE8.
Josh Stodola
There's something whacky about my pages that's preventing this from working. But I think your answer is correct for most reasonable pages.
fsb
A: 
var position= $(window).scrollTop();

//some things here

$(window).scrollTop(position);

It worked for me in both IE8 and FF.

DDetto