Sunday, January 4, 2015

appendChild loses keyboard focus

Scenario : Multi-user editable task list in a web browser, running as a DHTML app.  Changes made by any operator automatically stream to all other operators.  Thus, the task list is frequently being updated by client-side javascript to show changes that have been made by other operators.

Additionally, each entry in the list has an editable text input field that can receive keyboard focus and allow the operator to write notes.

As the contents of the list change, you're likely ultimately going to be using appendChild or a related DOM-manipulation function to ensure each operator has a realtime view of what other operators are doing as they add and remove entries and drag items around to change their sequence.

Turns out, in Firefox at least, that relocating a DOM element causes it to lose keyboard focus.

So for example, suppose Fred is busily typing a note into the text input field for work item #87, and Sally comes along and drags the same work item to reposition it, before Fred finishes his changes.  If we're not careful, Fred instantly sees the updated list order (which is good), but is frustrated because his typing is suddenly going to dev/null (not literally, but you get idea).  Tip : It is bad, bad user experience to steal the keyboard input focus when the user is not expecting it, and most especially so whilst he's in the middle of typing furiously at full speed!  Talk about a good way to destroy the operator's trust in the computer software system!!!  :o)

The solution is simple : onfocus for each input field, record in a global variable (or elsewhere) which input field currently has the keyboard input focus, and then after doing DOM manipulation that might've caused that input field to lose input focus (and assuming the input field is still relevant - e.g. if Sally deleted the work item, well, sorry Fred, your work is lost anyhows), simply invoke mostRecentlyFocussedElement.focus().

And now, your users take it entirely for granted that a) your application works very well; and b) actions by other operators are seen by all operators instantly but without disrupting the other operators.  As I say, the best software works so well that non-technical users will take it for granted and think nothing of it.  This trick is one trick in your arsenal for accomplishing that.

No comments: