Search code examples
javascriptasp.netasp.net-ajaxajaxcontroltoolkit

Setting div scroll bar location


I have a user control that has a treeview in it. Every time the user expands a node, it gets reloaded using an update panel. To prevent the user having to scroll through the treeview everytime it reloads, I want to capture the current div's scrollTop value, save it to a textbox and then after post back, take that value and reload it. Everything works except one odd behavior. This is the div:

<div ID="treePanel" runat="server"  class="treePanel"  onscroll="setScroll(this.scrollTop)" onunload="testScroll()" >
<asp:TextBox ID="scrollTb" runat="server" Text="" ></asp:TextBox>
<asp:TreeView ID="TreeView1" runat="server"  
OnTreeNodeExpanded="Node_Expand" CollapseImageToolTip="Click To Collapse" ExpandImageToolTip="Click To Expand">                     
</asp:TreeView> 
</div>

and this is the javascript functions, which is in the masterpage:

function setScroll(getVal){               
var getTb = document.getElementById("ctl00_ContentPlaceHolder1_rmsStepThree1_scrollTb")            
getTb.value= getVal
}

function testScroll(){
var getTb = document.getElementById("ctl00_ContentPlaceHolder1_rmsStepThree1_scrollTb")         
var getDiv = document.getElementById("ctl00_ContentPlaceHolder1_rmsStepThree1_treePanel")         
getDiv.scrollTop= getTb.value
}

The problem is that this wont work unless i add an "Alert()" in the javascript, like this:

function testScroll(){
var getTb = document.getElementById("ctl00_ContentPlaceHolder1_rmsStepThree1_scrollTb")         
var getDiv = document.getElementById("ctl00_ContentPlaceHolder1_rmsStepThree1_treePanel")  
alert('some text')       
getDiv.scrollTop= getTb.value
}

Can anyone explain why this is behaving this way and how to remedy it? I obviously can't have the alert in there.

thanks jason


Solution

  • Alerts fixing code normally means a race condition is in place. You are calling the code before the div is rendered fully. The alert is allowing it to be rendered fully. Shouldn;t you be setting the scroll position after the new content is loaded, not when it is unloaded?