How do I get the previously focused element in JavaScript?

The simplest way is to store a reference to document.activeElement within the mousedown event on the button, although this is a mouse-centric approach and won't work for button "clicks" from keyboards and other devices.

Live demo: http://jsfiddle.net/tEP6w/

Code:

var clearButton = document.getElementById("clear");
var previousActiveElement = null;

clearButton.onmousedown = function() {
    previousActiveElement = document.activeElement;
};

clearButton.onclick = function() {
    if (previousActiveElement && previousActiveElement != this) {
        previousActiveElement.value = "";
    }
};

A better approach would be to store a reference to document.activeElement as the button is about to receive the focus. However, this is a little tricky to achieve nicely in all browsers.


Create a global variable for storing the current focused element's id,

var cur_id;

call one function for onblur of each of elements and pass id

<input type="text" id="name" name="name" onBlur="setId(this.id)">

and write the set the id to global variable from that function

function setId(id) {
    cur_id = id;
}

and write a function for onclick of clear button, like this

function clear() {
    document.getElementById(cur_id).value = "";
}

When you click "clear" button, only element focused is "clear" button. You'll have to workaround it. (trigger onblur event)