Update 20.03.13: I updated the code so that it doesn't try to focus the field if the partial refresh hasn't influenced the active field.
Update 02.05.11: By request, I made a simple demoapp.
Update 22.11.10: Ajit Rathore found a weakness in the code. On partial refresh error -> unsubscribe to the event. I've added his patch to the code.
The code snippet below, in conjunction with my hijackAndPublishPartialRefresh function should fix the problem of fields losing focus when elements containing them are refreshed.
dojo.addOnLoad(function(){
dojo.subscribe( 'partialrefresh-init', function(){
// setTimeout needed to make it work in Firefox
setTimeout(function(){
var activeElementId = document.activeElement.id;
var focusSubscription = dojo.subscribe( 'partialrefresh-complete', function(){
// Only set focus if field hasn't been overwritten/lost focus
if( document.activeElement.id !== activeElementId ){
var activeElement = dojo.byId(activeElementId);
if( activeElement && /INPUT|SELECT|TEXTAREA/.test( activeElement.nodeName ) ){
// Set focus to element/select text
activeElement.focus();
if( activeElement.nodeName !== 'SELECT' ){
activeElement.select();
}
}
}
// Unsubscribe after focus attempt is done
dojo.unsubscribe( focusSubscription );
});
// In case of error -> remove subscription
var errorSubscription = dojo.subscribe( 'partialrefresh-error', function(){
dojo.unsubscribe( focusSubscription );
});
}, 0 );
} );
});
When a partial refresh is initiated, the browser is queried for the active element/the id of the element is stored in a variable. When the refresh is complete, focus is set to the element that had focus before the refresh.I've only tested it in a small testpage, so there may be bugs that I'm not aware of. Please let me know if you encounter any.
I've tested it/it should work in IE7/8, latest version of Firefox and Opera.
Share and enjoy!