I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.
A:
aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it
TheBrain
2009-10-06 13:59:22
are you sure? I wouldn't have thought that the form would blur at all, especially since it can't have focus in the first place.
nickf
2009-10-06 14:00:56
As I said in my question, the onblur event does not bubble. Please, read the question fully before spitting out an answer.
spudly
2009-10-06 14:03:33
+1
A:
ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating%5Fthe.html
NickFitz
2009-10-06 14:10:03
+1
A:
You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout
for IE:
if (myForm.addEventListener) {
// Standards browsers can use event Capturing. NOTE: capturing
// is triggered by virtue of setting the last parameter to true
myForm.addEventListener('blur', validationFunction, true);
}
else {
// IE can use its proprietary focusout event, which
// bubbles in the way you wish blur to:
myForm.onfocusout = validationFunction;
}
// And of course detect the element that blurred in your handler:
function validationFunction(e) {
var target = e ? e.target : window.event.srcElement;
// ...
}
See http://www.quirksmode.org/blog/archives/2008/04/delegating%5Fthe.html for the juicy details
Crescent Fresh
2009-10-06 14:16:10