tags:

views:

23

answers:

2

I would like to find out, in Javascript, which previous element had focus as opposed to the current focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this any help would be much appreciated

A: 

Well depending on what else your page is doing, it could be tricky, but for starters you could have a "blur" event handler attached to the <body> element that just stashes the event target.

Pointy
+1  A: 

Each time an element is focused, you'd have to store which one it was. Then when another element is focused, you could retrieve the variable for the previous focused element.

So basically, your single focus handler would do 2 things:

  1. Check if previousFocus is defined. If it is, retrieve it.
  2. Set previousFocus to the currently focused element.

Here is a quick demo with jQuery (you can use raw JS too... just fewer lines w jQuery, so it's easier to understand imo):

  // create an anonymous function that we call immediately
  // this will hold our previous focus variable, so we don't
  // clutter the global scope
(function() {

      // the variable to hold the previously focused element
    var prevFocus;

      // our single focus event handler
    $("input").focus(function() {

          // let's check if the previous focus has already been defined
        if (typeof prevFocus  !== "undefined") {

              // we do something with the previously focused element
            $("#prev").html(prevFocus.val());
        }

          // AFTER we check upon the previously focused element
          //   we (re)define the previously focused element
          //   for use in the next focus event
        prevFocus = $(this);
    });
})();

working jsFiddle

Peter Ajtai