I see that you’re using jQuery in your sample code, so we’ll use that to help with some of the heavy lifting.
The first thing is that the previousFocus variable should not be a variable, but instead a property on the form itself. That ensures that the information is kept in a location that is easily accessible to other code that works with the form, while also being as local as practical to the form itself. Global variables are considered to be bad form, so the most global that we can achieve while still remaining as local as practical, is the form itself.
If the form has no identifier, it needs one. You should make the identifier as relevant to the form as possible so if it were a form for filling in user details, you could give it an id of “userDetails”. Until that sort of info is known, I’ll go with “sampleForm”.
$('#sampleForm').prop('previousFocus', false);
Then in the blur handler, you can set that previousFocus property to be the element that triggered the blur event. But we’re getting ahead of ourselves here. How do we use jQuery to easily do things with form elements in the first place? You can use the ‘:input’ selector, but we don’t want the tab button (which I’ll currently assume has an id of “tab”) to also be included in that, so we can tell the selector to exclude that.
Because this is jQuery now, we can provide the function directly to the blur event itself:
$('#sampleForm :input:not(#tab)').blur(function () {
...
});
It’s inside that event where we’ll set the previousFocus property of the form.
With event functions within jQuery, the this keyword can be used to refer to the element that triggered the event, and each form element contains a natural reference to the form itself, so all we should need to do within that function is:
$(this.form).prop('previousFocus', this);
Which will assign the element (via the this keyword) to the previousFocus property of the form.
That’s done so that later on with the tab button, the click event for it can refer to that previousFocus property to find out the most recent form element that previously had the focus.
Now there’s only (and it’s a big only) the tab click event to deal with.