Get "previous" element which had focus after tabbing

rk8785 picture rk8785 · Jul 21, 2015 · Viewed 8.1k times · Source

I am working on keyboard management and stuck on this issue where I need to find the element which had focus before tabbing. For example lets say I have a list in html which looks like

1. Folder button
2. Account button 
3. Setting Button
4. More Button
5. SignOut Button

Lets say the element which has focus now is Account button. Later I press tab and the focus moves to Settings. Now when I do document.activeElement I will get Setting button but how do I get the previous element which had focus (in this case it would be Account button). The current hack that I have done is storing the element which has focus and using it later when needed. The problem with this way is the previous element sometimes still retains the focus on tabbing even though I manually remove its focus by tabIndex =-1. Please ask for any clarification. Thanks in advance

This is what I am doing now by storing the old value but I want a better way of doing it. May be on the fly(ie when focus changes) without storing it

if(on arrow key events){
oldElementFocus = document.activeElement; //store previous element
do stuff...
}
if(event.keyCode && event.keyCode == 9){
// on tab I want to edit the attributes of the previous element
oldFocusedElement.tabIndex = -1;
}

Answer

gautsch picture gautsch · Jul 21, 2015

I would listen for the keydown and check for the tab key. then update two variables. One that stores the lastFocused key and another that stores the current focus.

(function(){
    var lastFocus,
        currentFocus = document.activeElement;

    function getLast(event) {
        if(event.keyCode && event.keyCode == 9) {
            lastFocus = currentFocus;
            currentFocus = document.activeElement;
            alert(currentFocus);
        }
    }

    document.addEventListener("keydown", getLast, false);
})();

here is a fiddle that demonstrates this https://jsfiddle.net/dgautsch/qdx7hc7d/