Search code examples
javascriptvb.netscrollobject-expected

window.scrollTo(...) error: Microsoft JScript runtime error: Object expected


I know there are a lot of post about this, but i've been looking to do this all day. What i try to acheive here is to click on a row in a GridView, then bring the page to scroll to that position, like an anchor in html would do.

This, is my link that i'll use to scroll. I call a function in my js file. This is in my GridView.

<asp:LinkButton runat="server" OnClientClick="window.scrollTo(0, GetPosition(this))" CommandName="select" ID="InkSelect" Text="SELECT" />

Then, i call this function in my js file, linked like this, just in case:

<script type="text/javascript" src="~js/monjs.js"></script>

In monjs.js, here is the function:

function GetPosition(element) {
var top = 0;
var e = document.getElementById(element);
while (e.offsetParent != undefined && e.offsetParent != null) {
    top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
    e = e.offsetParent;
}
return top;}

And Visual studio is highlighting this line:

...... <a onclick="window.scrollTo(0, GetPosition(this));" .....

I tried many other way to do this, registering a script in the vb file, hardcoding window.scrollTo(0,100) in the onclick attribute, i'm out of ideas. I tried row.focus, don't mention this one. Thanks. enter image description here


Solution

  • ok I managed to do something. AFter many many tries... i used this in my aspx file:

    <asp:LinkButton runat="server" OnClientClick="return Move(this);" CommandName="select" ID="_row" Text="SELECT" />
    

    In my aspx.vb file, i used this in my page load function:

    Dim myScriptName As String = "MovePageScript"
        If (Not ClientScript.IsClientScriptBlockRegistered(Page.GetType(), myScriptName)) Then
            Dim myScript As New StringBuilder()
            myScript.Append("<script type=""text/javascript""> function Move(element) {")
            myScript.Append("var top = 0;")
            myScript.Append("var e = typeof element === 'string' ? document.getElementById(element) : element;")
            myScript.Append("while (e.offsetParent != undefined && e.offsetParent != null) {")
            myScript.Append("top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);")
            myScript.Append("e = e.offsetParent; }")
            myScript.Append("window.scrollTo(0, top);")
            myScript.Append("return false;")
            myScript.Append("} </script>")
            ClientScript.RegisterClientScriptBlock(Page.GetType(), myScriptName, myScript.ToString(), False)
        End If
    

    And used this in my web.config file:

    <pages maintainScrollPositionOnPostBack="true">
    

    It cancels the selection of the row but at least it works... I'll have to check now if I can get this to work with Telerik's Ragrid XD