Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Strange focus behavior on Firefox 3+

1 min read

Apparently it seems as if Firefox has changed the way the focus is set on the page starting with version 3+.
When using the <yourcontrol>.Focus() method on Asp.net the current behavior is that Firefox automatically scrolls the page till the "focused" element is in the very last row of the screen. This is really nerving, especially if you're using Asp.net Ajax UpdatePanels. In that case you have that as soon as the asynchronous postback caused by the UpdatePanel returns, your page starts to jump around (if on the server-side you set the focus on some control).
I used the following piece of code inside some Helper class to solve the problem. The idea is basically to use the ScriptManager to register a JavaScript which is launched as soon as the postback comes back to the client.
public static void SetFocusByJavaScript(Page page, Control targetControl)
{
SetFocusByJavaScript(page, targetControl.ClientID);
}

public static void SetFocusByJavaScript(Page page, string clientID)
{
string uniqueScriptId = String.Concat("focusScript", clientID);
string scriptBody = String.Format("setTimeout(\"$get('{0}').focus();\", 100);", clientID);
ScriptManager.RegisterStartupScript(page, page.GetType(), uniqueScriptId, scriptBody, true);
}
By the way this would be a nice candidate for writing an extender method on the control class...Should be realizable in an easy way.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus