Maintain Scroll Position after Asynchronous Postback

Do you want to maintain the scroll position of a GridView, Div, Panel, or whatever that is inside of an UpdatePanel after an asynchronous postback?  Normally, if the updatepanel posts back, the item will scroll back to the top because it has been reloaded.  What you need to do is “remember” where the item was scrolled to and jump back to there after the postback.  Place the following script after the ScriptManager on your page.  And since the _endRequest event of the PageRequestManager happens before the page is rendered, you’ll never even see your item move!

<script type="text/javascript">
    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
        xPos = $get('scrollDiv').scrollLeft;
        yPos = $get('scrollDiv').scrollTop;
    }
    function EndRequestHandler(sender, args) {
        $get('scrollDiv').scrollLeft = xPos;
        $get('scrollDiv').scrollTop = yPos;
    }
</script>

139 Comments

  • This small script possibly saved my life. Very easy implementation in this way.

    Thanks a lot. :)

  • Pure sweetness - after looking all over for something like this, this is a easiest and most elegant solution yet.

  • Looks like just the thing I was after - except...
    The scrollDiv in my case is a panel which is the PopupControlId of a PopupcontrolExtender. The panel itself has an updatepanel (to handle the selection/deselection of a checklistbox) inside it (as well as outside). Am I just missing something on the $get (i.e. to find my panel inside of a nested updatepanel)? - Any help appreciated - as I'm almost there on a dropdown multi-select combo like control.
    Thanks

  • Great help!
    Thank you very much!

  • It has really helped me.Thanks a lot!

  • Excuse my ignorance, but can I put that code in a jscript file, and how exactly would I reference it in a div tag?

    Thanks.

  • If we added the div tag, and the size of the control is dynamic based on the conditions, it will not be good in the UI.

  • You are a ROCK........

    Thankyou verymuch

  • If you are having a problem with sys undefined... make sure you put this bit of script in your code after your gridview control. This will allow enough time for the scriptmanager to load from your master page if you are using one.

  • I would like to say this post saved me hours. Cheers mate.

  • I have tried this trick but it doesn't work for me

    I am applying to div tag for rating control? Is it has something to do with control.... Somehow i can't able to get through your tip. I am using Master Page/ Content Page scenario.

    http://dotnetguts.blogspot.com/2008/12/rating-control-ajax-display-message-on.html

  • Any know how to get this to work when the script manager is in the master page and the panel (the position of which I need to maintain) is in the content page? I tried putting the above JS code at the bottom f the page I get a JS error saying 'Object required'. I think this is the line that does it

    Sys.WebForms.PageRequestManager.getInstance();

    and I think it is because my script manager is in the master page.

    BTW, this works fine if I use it on another aspx page which has no master page.

  • If you're trying to reference a Panel or a div that's runat server then the JS script needs the control's unique id, so I thought you could just do something like: $get('GridviewTestForArtie.ClientID') BUT this never retrieved the ClientID in my testing. One alternative is to just use an HTML DIV tag that's not run at the server so the ID you give it isn't changed, another alternative is to get the ClientID - the .Net generated ID (do a View Source or something) and put that in the JavaScript.

    Also, this block of JS code needs to be after the DIV, Panel, whatever it is you're referencing. If your ScriptManager is in your master page, and you put the code there but before your ContentPlaceHolder then it's not going to work. I believe it would be best to put it in the content page after the DIV or Panel. I did that and it worked for me.

  • You saved my life too...

  • This is about as helpful as helpful can get... awesome

  • Is there any way you can convert this to work witha master page. All of the java script has to be run from the master page and this seems to break the code.

    Thanks.

  • Thanks a million!!! Saved me hours. You rule.

  • Help! I have used the script as given on a textarea within an Updatepanel. The textarea dimensions are set. The scrolltab does hold postion but I am getting some serious textarea flicker upon asynchronous postback. Is there a way to supress the flicker?

  • Thank y ou Soooooooooooooo Much it is a great solution

  • Sweet. Nice one mate! Works a charm

  • I have multiple areas with scrollbars in separate updatepanels on the same page. I placed the script immediately after one scrollable area and the scroll bar stays as advertised. great work. However, please tell me how to handle several on one page. This approach is not working with multiple scrollables. The later one gets the scrollbar functionality I want. Why I can't I place it just after the script manager and have it work? Thanks.

  • Thanks a lot ....!!!

  • Thanks. This helped a ton and saved a lot of time.. kuddos to you.

  • Simply Awesome! worked great. Thank you, Thank you, Thank you!

  • Thanks, this really helped!

  • DUDE, I FREAKING LOVE YOU FOR THIS, I FEEL LIKE CRYING...I'VE SPENT FOREVER LOOKING FOR SUCH BEAUTIFUL CODE...FREAKING AWESOME

  • Great stuff. Thanks a lot :-)

  • Hi - thanks so much you are a genius! This is by far the simplest approach I've found on the web and the only one that worked in my situation! Awesome!

  • I love you. I've tried to do the same for three days and I wasn't able to do anything.
    You're brilliant

  • i used the update panel , and inside the update panel i have a scrolling div with gridview. but above code is not working in my application, so help me.

  • Kudos to you sir. Thanks for the great insight. This also helped me out greatly!!

    :)

  • Lifesaver! Thanks!

  • Great post ..

    Really helpfull

    Thanks

  • YOU ARE TOO KIND WITH THIS!

    HUGE THANKS!

  • Thanx a lot yar,
    Realy very Great/Genius work yar.

    Thanx a lot

    Abhishek

  • This is great, thanks

  • PERFECT! Easiest soluton BY FAR after Googling for over an hour!

  • Hi, I make it work with masterpage, you simply need to put the script at the end of the page, just before the tag, and replace the scrollDiv name by something like this :

    xPos = $get('').scrollLeft;

    Pretty good script!

  • Hi,

    I have a little problem with this solution (and with every other solution I've tried for maintaining the scroll position):

    The div returns to its previous position and it works perfectly when it's only scrolled vertically or only scrolled horizontally.
    But, if the div is scrolled vertically AND horizontally, after the partial postback the page flickers.
    For some small amount of time I can see the top of the div before it scrolls down into position. If I switch the order of the lines that set scrollTop and scrollLeft, so that scrollTop is set first, then I can see, for some small amount of time, the leftmost side of the div, before it scrolls right to its previous position.

    This happens on Firefox 3.5 and IE7.

    I was wondering if there's a way of avoiding this flickering, perhaps some way to tell the browser to set both scroll values at the same time?

    Thanks!

  • Anyone tried using this jscript for a gridview in a panel that's part of a user control loaded dynamically into a tab container at run-time?

    I can't get the javascript to run at all.


    argh

  • Hey,

    I am spellbound by this script, realy great script to handle scroll position.

    Shiv

  • Best idea I have run across yet. I got it working in less then 5 minutes. My scenario was this

    Master page, content sections
    user control in body content section wrap inside update panel

    User control page had a panel with a listview which scrolls vertically. Just had to add the javascript to the button of my user control and change the scrollDiv parts to

    Thanks a million!

  • Can any one show a ful working example with master page, content, and gridview?

  • WOW. After a year on and off messing with different solutions, half could never get to work, half not working as I hoped I can't believe I found this one. Simple + Works = PERFECT

    watercloud: Make sure you put this routine the LAST thing before the tag on the content page and change 'scrollDiv' to actual asp control name (mine was 'divFilterList' and should work. I was putting after ScriptManager on Master Page with no luck.

  • WOW . A lot of thanks for your great help.

  • After Googling for 2 days, I run into the this. Easiest solution by far. i got it working in a minute

  • Billiant. A life saver. Thank you.

  • This solution rocks! Really, after scouring EE I found a link to this page. Wonderful solution as I have grids nested in tables. This is SWEEEEET!

    tyvm!

  • THANKS A LOT BRO.... SAVED LOT OF TIME

  • Thanks man, i have been looking for this solution for a long time.. Thanks a bunch

  • Thanks a lo man, it totally made my day,,, great code :D

  • I placed the code the scrolling is working but i have a update panel in aspx page which it is inherited by master page and i placed the above code but the update panel is not working?

    can i get the solution for the above problem

  • thanks man

  • Dear All,

    It is working fine for me when the ListBox SelectionMode ="Single", But it is not working SelectionMode ="Multiple"

  • Hi Andrew,
    thank u so much,
    thank u very much.

  • Hi Andrew,
    thank u so much,
    thank u very much.

  • Not only did it not work, but it somehow managed to prevent my asynchronous postback from working- the entire page would postback and refresh.

  • Hi when I set this code I am receiving a value of "0" for scrollTop whenever I try using this code
    $get('scrollDiv').scrollTop;

    which means it doesn't work.

    I have a Masterpage and a content page and repeater with a user control in a panel. Any ideas?

  • guys, I have the following scenario.

    I have multiple Panels in my page. just one is visible=true; all others are visible=false. When I clik on a particular button I create server-side with async postback one panel visible=true. In this panel I have a div with scroll, also the javascript provided in this post. In the div with scroll I have a repeater control. when I select something from repeater, an asyc postback it is happen but the scroll is not maintain the position. Also I can not find the div and script in the client side view source code. but in my code is iserted exactly after the div.

    If I put everything in a visible panel first time it is working fine. How can I sove this problem for visible false panels?

  • Does it work with mozilla browser? i tried with mozilla and its not working.

  • i think this is the best code i see to solve this issue.

    Great job.

  • super!
    works on firefox 3 also.

  • Just Great! Thanks a lot!

  • Its great, Keep it up !!!

  • Excellent! Saved me lot of time! Thanks.

  • Three words for you...
    Awesome Awesome Awesome...

  • Great Work Bro........... works with listbox selection mode single although I am not able to get it working for selectionmode= multiple .......... Thanks a lot

  • Great, that's what I was looking for half of the day.

  • I may be a bit late to the party, but thanks for the code. It was exactly what I was looking for.

  • Great job, Thanks man!!!!

  • didnt workd......................delete this code.................i wasted alot of time working on this..............

  • for me this javascript code is not working
    i dont knw the reason

  • mantap, terima kasih banyak yah. aku pusing solusinya ternyata disini. thx a lot

  • If you don't know how to use this code then don't comment to delete this code. Well great article that was. Helped me in saving a lot of time. Thanks again.

  • Not working in chrome

  • Fail. Doesn't work for Master page as many many many people have pointed out.

  • Have you tried it in chrome?
    Not working for me in chrome and safari.But for other browsers works fine.

    Please provide a solution

  • thanks a lot man

    great work

  • Thanks a lot man,nice stuff.

    I was using Panel inside Master Page and ContentPlaceholder

    Follow below steps
    Remove scrolldiv by
    ctl00_ContentPlaceHolder1_Panel2

    put your panel name instead of Panel2(it is my panel name)

    It's working for me.


  • its not working for me..
    heres my code if you can help





    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
    xPos = $get('MsgDiv').scrollLeft;
    yPos = $get('MsgDiv').scrollTop;
    }
    function EndRequestHandler(sender, args) {
    $get('MsgDiv').scrollLeft = xPos;
    $get('MsgDiv').scrollTop = yPos;
    }




















  • What a freaking life saver! Thanks!

  • Thanks - helped me heaps
    This also worked with jScrollPane - adapting it slightly - for some reason for me the maintainPosition of jScrollPane was not working with UpdatePanel updates. So i added
    the follow to my js

    var scrollingDivToReScroll;
    var xPositionScroll;
    var yPositionScroll;

    $(function () {
    initialiseScrollPane();
    });

    function pageLoad() {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequesetHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    }
    }

    function beginRequesetHandler(sender, args) {
    if (scrollingDivToReScroll != null) {
    var api = scrollingDivToReScroll.data('jsp');
    if (api != null) {
    xPositionScroll = api.getContentPositionX();
    yPositionScroll = api.getContentPositionY();

    // shall we change the cursor to a wait cusor
    $('body').css('cursor', 'wait');

    }

    }
    }

    function endRequestHandler(sender, args) {
    initialiseScrollPane();
    if (scrollingDivToReScroll != null && xPositionScroll != null && yPositionScroll != null) {
    var api = scrollingDivToReScroll.data('jsp');
    if (api != null) {
    if (xPositionScroll != null) {
    api.scrollToX(xPositionScroll);
    }
    if (yPositionScroll != null) {
    api.scrollToY(yPositionScroll);
    }
    }
    }
    $('body').css('cursor', 'auto');
    }

    function initialiseScrollPane() {
    scrollingDivToReScroll = $("#styledScroll").jScrollPane(
    {
    showArrows: true
    }
    );
    }

  • Awesome Work...Keep Posting and Helping others !!! :-)

  • Great posting, simple & effective.

    Thanks

  • Save me tons of frustration! Thanks!

  • Thanks a lot. This worked for us.

  • Thanks a lot :)

    I tried so many ways but this is the best among all..

  • This is Great It works fine.
    for my case I have a master page and in it I have a div tag around the contentplaceholder






    So all I had to do is replace scrollDiv' for 'divContent' and it worked like a charm.....
    THANKS!!!!!!!!

  • When I am using above code..

    I am getting error of java script...object required..

  • Kudos to you. I've tried several other methods, none of which have worked. This one worked a treat.

  • add MaintainScrollPositionOnPostback="true" attribute to the page's @ Page directive

  • I dont have words ,but this was one of the important and the best ever solution i had for the scroll position of controls for any asp.net page..Thanks a LOT...................................................................................................................................

  • Can anyone give me a small way to accomplish this?

  • Thanks....Work perfectly.. too good...

  • Epic Effort. Thanks for sharing.

  • Sylvia, many thanks for the jScrollPane code - works great on my implementation also.

  • superb script Andrew! This was vexing me for hours and hours. Your script saved my day!

    Brutus

  • What can I say that hasn't been said ... you da man!

  • THANK YOU SO MUCH!

  • You absolute legend!

  • Thanks A lot .
    I hv been searching this for 2 days..
    U saved my life.

  • Great,,, Problem solved...... Thanx

  • Thanks a lot.....I dont have words to explain

  • Works great in most cases. One case where I still get a flicker: I have an elapsed time clock (Ajax asp.Updatepanel, asp:textbox and asp:timer) that updates once per second. If the user scrolls quickly (between ticks), no problem. If the user scrolls slowly, the screen jumps.

    Any ideas to work around that? Is there a way to detect that the user is scrolling and disable the timer until they stop?

  • Very cool. Does what I wanted ; )) I am doing some processing on SelectedIndexChanged to limit the user to only 10 selections. My multi select listbox was scrolling back to the top on autopostback.

  • Thanks a ton!!! it worked perfectly fine..

  • This does not work for content page that uses master page. Can you please tell me how to maintain scroll position for page that uses master page?

  • Thanks dear. it's working fine..

  • Thanks man....!!! working great.....

  • Hey Spark I found the solution solution to maintain scroll position for page that uses master page .
    Add following code in your script :

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_beginRequest(beginRequest);

    function beginRequest()
    {
    prm._scrollPosition = null;
    }

    I have also added MaintainScrollPositionOnPostback="true" in page tag


  • You're my hero! I've been trying to figure this out for waaaaaaay longer than I'd care to admit.

  • Too Coll, great job and thanks alot

  • it did not wrk for me , i am using json to make dynamic html in div
    please help

  • great help

    Thankyou

  • Very simple and useful script

  • Guys guys guys,

    Please provide "HEIGHT" to the Div for those cases if it is not working.

  • Thanks for this very easy solution..

  • Dude, that script totally worked. Thanks.

  • Fantastic....after long hours of browsing, I found this solution works fine

  • Thanks ......
    Really it saves my life

  • Fantastic....after long hours of browsing, I found this solution works fine

  • Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks Thanks
    :)

  • Thanks............you are great......... :)

  • I'm going to have to steal Wilson West's line. PURE SWEETNESS!

  • Dude ur jus awsome.
    God bless u.

  • Excellent, best regards!

  • Sys.WebForms.PageRequestManager.getInstance()

    i get the error on Sys is not defined ..

    how to solve pls help me

  • Excelent , easy implemnetaion, thanks for your work

  • FANTASTIC!
    After searching for hours and trying several (some rather complex) javascripts, I finally found this: elegant, small, and above all: WORKS INSTANTLY!
    Great work, thanks a million!

  • GREAT POST!! that piece of code was a life saver.
    Modified it a bit and all 3 of my grids are maintaining thier scroll position

  • Thanks Very good post it solves my problem thanks alottttttt

  • No its not working for pages that have master page could any one pls help me out
    i have master page and i use that on my entry page on my entry page i have 4 cascaded dropdowns but i am unable to maintain scroll position when i select one

  • that's a really nice piece of code! :) Keep posting

  • Worked for me with Master Pages. Reference the ID of the panel this way

    yPos = $get('Content_RolesAdmin').scrollTop;

    Where Content is the ID of the contentplaceholder in the master file and RoleAdmin is the ID of the panel.

    Thanks

  • Great one. Many Thanks

  • I have tried this script on my page and it doesn't work. Here are the particulars of my situation:

    1) Page is ascx contained inside an iFrame.
    2) There are 4 UpdatePanels, each one needs to be controlled by this no-scroll script.
    3) All 4 UpdatePanels are contained inside of one Div with an ID of "scrollDiv".
    4) The script seems to have zero affect on the page. It scrolls just as before.

    Can anyone help?

  • Great. It worked like a charm.

  • Thanx for such a help. . . .its a Great work

  • It is not working for me.
    I have master page.
    Included the above JS in contact page just before
    I need to maintain scroll position each time when poast back happens. But it is not working. Any ideas

Comments have been disabled for this content.