views:

240

answers:

2

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

+2  A: 

Yes, you can get the target like this:

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

(I think I found this on StackOverflow somewhere).

Charlie Flowers
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 Sastry
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
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 Sastry
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 }
BrokeMyLegBiking
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
+1  A: 

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 Sastry
Ify, but that seems to be the case.
Justin Johnson