Home
 Index > JavaScript > Go to scroll position on form post back

JavaScript:  Scroll Position , Form PostBack

Go to scroll position on form post back

When a form performs a postback, automatically scroll down the page to the scroll position prior to postback.

Added on 18 Jun 2008

Scenarios:

Scenario Summary:
When a control, such as a dropdownlist causes the form to postback, the page should automatically scroll down to the scroll position prior to postback (i.e., to the web control that caused postback).
Scenario Details:
Added on 18 Jun 2008

Solution Summary:
When the user clicks the control that causes postback, a hidden field should hold the value of the current scroll position. When the form loads, the hidden field should be checked for a value. If a value exists, scroll to the position specified.
Solution Details:

This will require to small JavaScript functions:

function SetTarget(id) {
     document.getElementById(id).value = document.body.scrollTop;
}
function GoToTarget(id) {
    
if (document.getElementById(id).value != '') {
          document.body.scrollTop = document.getElementById(id).value;
          document.getElementById(id).value = '';
     }
}

Add SetTarget to the onclick (or onchange) event of the control that causes the page to refresh, and call GoToTarget every time the page loads (i.e., add the function call to the very end of the body).
continue
<body>
<
form>
    
<!-- enter page content that -->
    
<select id="myDropDownList" onchange="SetTarget('hdnTarget');doPostback();">
    
     <option>1</option>
    
     <option>2</option>
    
</select>
    
<input type="hidden" id="hdnTarget">
</
form>
<
SCRIPT language="javascript">
    
GoToTarget('hdnTarget');
</SCRIPT>
</
body>


To add the SetTarget function to the onchange event of a dropdownlist Web Control with AutoPostBack enabled, you can add the "onchange" attribute in the VB code:

myDropDownList.Attributes.Add("onchange", "SetTarget('hdnTarget');")

Was this solution useful? Yes No Added on 18 Jun 2008
Rating: 

Copyright 2010 © E-Centric, Inc. | Terms of Use