4

I am firing some code onblur() of a textbox. But I want to do something different if the user clicked on the cancel button to cause that onblur(). Is there a way within the onblur() event handler function to know what the control is that is about to receive focus and react acordingly?

-Joseph

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
BrokeMyLegBiking
  • 5,898
  • 14
  • 51
  • 66

2 Answers2

6

Yes, you can get the target like this:

var target = event.explicitOriginalTarget || document.activeElement;

(I think I found this on StackOverflow somewhere).

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Charlie Flowers
  • 17,338
  • 10
  • 71
  • 88
  • 3
    Here is the related discussion - http://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to but the accepted answer only works in IE, not in Firefox (3.6) – Chetan S Jan 30 '10 at 00:11
  • I haven't tested it in many browsers, but I think you misunderstood. The way I read that just now, this works in all Firefox browsers except for 3.6. So it sounds like a bug they will be fixing soon in 3.6 perhaps. Plus, I believe (without having verified) that it works on Safari, Opera, etc. – Charlie Flowers Jan 30 '10 at 05:38
  • The author of the accepted answer in the other thread posted a reply to my comment. It does work in 3.6 but with a caveat. He also says it doesn't work in webkit browsers at all. – Chetan S Jan 30 '10 at 21:02
  • 1
    I am using just IE, so this works great for me. I tested it out, and it works like a champ! On my validation framework (jquery validation) I just check if the target button ends with the phrase "Cancel" onfocusout: function(element) { var target = document.activeElement; if (target != null && target.id.match(/Cancel$/)) { return true; } – BrokeMyLegBiking Feb 04 '10 at 16:21
  • Glad to hear it. I also am on an IE project, and it has been pretty thoroughly tested in our product for about a month now. – Charlie Flowers Feb 05 '10 at 07:23
1

I don't think there is a built in way, but you can hack together something by attaching focus events to all the form elements and setting some globally accessible variable about who received focus.

Something like this (you may want to fine-tune the time values):

var focusedElem = null;
var focusedTime = 0;

$("input", "#myForm").focus(function() {
    focusedElem = this;
    focusedTime = new Date();
})
.blur(function() {
    setTimeout(function() { //set a small timeout to wait for the other control to receive focus and set itself as focusedElem
        if (focusedElem && (new Date() - focusedTime) < 15) {
            //do Something with focusedElem;
        }
    }, 10);
});
Chetan S
  • 23,637
  • 2
  • 63
  • 78