Restoring page scroll position with jQuery
Asked Answered
B

7

42

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.

Banns answered 5/1, 2010 at 20:54 Comment(2)
That should work. Can you post a demo? Which element is scrollable?Countrybred
Only the page is scrolled. No elements within the markup are scrollable. I'll see what I can do about a demo.Banns
M
47

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

var scroll = $(window).scrollTop();
// yada
$("html").scrollTop(scroll);
Mckinleymckinney answered 5/1, 2010 at 20:58 Comment(6)
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?Banns
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.Mckinleymckinney
There's something whacky about my pages that's preventing this from working. But I think your answer is correct for most reasonable pages.Banns
I think I just found an issue here: If you develop and experiment with setting scrolling position, remember that the browser tries to be clever and tries to restore previous scrolling positions. In Chromium (version of Ubuntu 12.04), reloading (Ctrl-R) doesn't do the trick, I have to retype (Ctrl-L Enter) the URL.Neurosis
Need to use $(window).scrollTop(scroll); in Chrome (29).Charitacharitable
Thanks for the tip! I ended up using $("html, body").scrollTop(window.scrollY - 1000); to scroll up 1000 px.Weatherly
E
30
var position= $(window).scrollTop();

//some things here

$(window).scrollTop(position);

It worked for me in both IE8 and FF.

Eva answered 7/1, 2010 at 21:8 Comment(3)
Also it makes more sense.Hagai
This answer also works for scrolling elements other than the window, for example if you have a modal with scrollable content you just replace window with "#your-element-selector" and it works like a charm!Commandment
This answer works in IE, FF and Chrome. But in FF and Chrome the page has a flashing. It goes to top and then to the current position. I used 'event.preventDefault();' , but nothing changed.Ineducation
M
4

Be sure to use return false; to terminate your function(){} construct.

The event trigger may be trying to execute the default action of the target DOM element i.e., < a href="" >;

Militia answered 25/9, 2012 at 17:26 Comment(1)
omg finally! thanks to your comment I could denegate the event so the page doesn't scroll to its previous position all the time. Useful tip, thanks!Attorney
E
1

Are u use aspx? if it's aspx:

$(document).ready(function () {
        //------------ scroll-------------
         
        $('body').scrollTop(document.getElementById('<%=hdScroll.ClientID%>').value);
            
        $(window).scroll(function () {
            $("#<%= hdScroll.ClientID %>").val($(window).scrollTop());
            //alert(document.getElementById('<%=hdScroll.ClientID%>').value);
        });
       });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <asp:HiddenField Id="hdScroll" runat="server"></asp:HiddenField>
Exemplum answered 19/8, 2015 at 16:44 Comment(0)
I
0

You could periodically check the div outerHeight, and set the scrollTop property once the div rendering has crossed the scroll value.

var g_Interval ;
var g_ScrollTop ;

function checkAndAdjustScroll() {
    var height=$('#content').outerHeight() ;
    if(height>g_ScrollTop) {
            $(window).scrollTop(g_ScrollTop) ;
            clearInterval(g_Interval) ;
    }
}

And whenever you update your div with AJAX content, do this

g_ScrollTop=$(window).scrollTop() ;
g_Interval=setInterval(checkAndAdjustScroll, 100) ;

You might need to make adjustments based on the offset of your div from the top of the page

Idempotent answered 12/7, 2013 at 11:10 Comment(0)
G
0

Try to use .html() instead of .replaceWith():

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

I don't know about possible performance bottlenecks here, but it did the trick for me when I was trying to preserve the scroll position of a div, and it seems to do well with the scroll position of the entire page as well.

Glossary answered 2/7, 2018 at 15:3 Comment(0)
B
0

function gotoDiv(divId)
{
   $('#'+ divId).get(0).scrollIntoView();
}
.ScrollStyle
{
    max-height: 200px;
    overflow-y: scroll;
}
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div id="main">

<h2 style="text-align:center;"> ScrollInto View Demo </h2>

<div id="first" style="background-color:skyblue">
<h3>This is First Div </h3>
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
</div>
</br></br></br>
<div id="second" style="background-color:yellow">
<b>This is Second Division? </b></br></br></br>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
</div>
</div>
</br></br>
<button class="btn btn-primary" onclick="gotoDiv('second')">Goto Second Div</button>
<button class="btn btn-primary" onclick="gotoDiv('first')">Goto First Div</button>
<button class="btn btn-primary" onclick="gotoDiv('main')">Gotop</button>

Use the particular element's Id to scroll that element into the view. Hope this help.

var element = document.getElementById("elementId");
element.scrollIntoView(); 
Broadbrim answered 28/9, 2022 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.