I have code to capture the control with the current focus on pageLoading and set the focus back to that control on pageLoaded, but it only ever works the first time, not the second. For example, I have two textboxes that both act as Asynch Postback triggers. If I change data in one, and tab out, the AJAX performs properly, and the pageLoaded event sets the focus to the control I just tabbed to. If I change data in the next textbox and tab out, the AJAX performs properlly and the pageLoaded event fires (F12 breakpoints show it does) but the focus is then gone. It does not matter which of the two textboxes I change first, the second one always fails. Even if I have a single textbox that fires an AJAX postback, the first time I tab out, the focus is set properly, if I go back to that same textbox, change the data and tab out again, it does not.
Any help would be greatly appreciated!
Here is the Javascript that is set as a ScriptReference in the ScriptManager:
/*
Script adapted from
http://couldbedone.blogspot.com/2007/08/restoring-lost-focus-in-update-panel.html
*/
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof(window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof(document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof(focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else
{
focusTarget = null;
}
prepareFocusedControl(targetControl);
if (focusTarget)
{
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else
{
prepareFocusedControl(targetControl);
}
}
function pageLoadedHandler(sender, args) {
if (typeof(lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
function prepareFocusedControl(targetControl)
{
try
{
targetControl.focus();
}
catch(err)
{
}
}
var keys = new Array();
function keyCapture() {
var key = event.keyCode;
keys[keys.length] = key;
}
Sys.Application.add_init(appInit);