So in this project that i’m working on at my workplace, we have a bunch of products’ details displayed in a grid whose prices can be overridden by the admin user. The user has to check a “Override” checkbox, which would enable the price textbox. Uncheck obviously means the price cannot be overridden and textbox would be disabled. For business reasons, we had to use the autopostback option for the override checkboxes.

Anyways…the challenge was that there were atleast 25 or more products displayed in the grid and thus as you can imagine, when the user checked the bottom most product’s override checkbox the page posted back and auto-scrolled to the top of the page. This could be very annoying to the user and apparently, Smart Navigation was neither smart nor navigated anywhere expected and forced me to rely on Javascript to solve this issue.

After some googling, here’s how i fixed it.

There’s a javascript property called location.hash

bq. hash is a property of both the Link and the Location objects and is a string beginning with a hash (#). It specifies an anchor name in an HTTP URL.

For example, if the url is something like http://www.example.com#anchor

then #anchor is the hash property.

What this means is that if you have the id of an element in the page, you can set the focus to that element, when the page loads by using the location.hash property.

If you are using the a element , then you may use either the id attribute or the name attribute.

So i wrote a little procedure in the aspx’s code-behind that looks like this:

Private Sub anchorScript(ByVal productId As String)
     Dim Script As String
     Script &= "" & Environment.NewLine
     Script &= "var anchorLocation='#" & productId & "';" & Environment.NewLine
     Script &= "location.hash=anchorLocation;" & Environment.NewLine
     Script &= "" & Environment.NewLine

     If (Not Page.IsStartupScriptRegistered("anchorScript")) Then
           Page.RegisterStartupScript("anchorScript", Script)
     End If
End Sub

And called this procedure after doing the necessary stuff in the checkbox’s CheckedChanged event handler. Typically this would be the last line in the sub.

The above procedure registers a javascript function that when rendered, would look like this :

var anchorLocation='#'
location.hash=anchorLocation;

This would tell the browser to focus on the element that has an id(passed into the anchorScript procedure).

Simple. Worked like a charm.

Leave a Reply