22

Is it possible to have focus events bubble in protoype?

I am trying to prevent having to assign an observer on every input element.

<script language="javascript" type="text/javascript">
document.observe('dom:loaded', function() {

    // Doesn't work
    $('editForm').observe('focus', function(evnt){
        console.log('FOCUS!');
    });

    // Works
    $('editForm').select('INPUT').each(function(elem) {
        elem.observe('focus', function(evnt){
            console.log('FOCUS!');
        });
    });

}); 
</script>

<form method="post" name="editForm" id="editForm" action="">
<input type="text" name="foobar" />
</form>

2 Answers 2

43

focus and blur events don't bubble.

You can fire event-handler during capturing phase. When using standard DOM methods, you would write

document.addEventListener('focus',function(e){/*some code */}, true);

the 'true' value is here most important.

The problem is that IE doesn't support capturing phase of event propagation, but for IE you can use focusin and focusout events, which - unlike focus and blur events - do bubble. I recommend reading an article on this topic written by Peter Paul Koch. Other browsers (Firefox, Opera, Safari) probably (I didn't test it) support events like DOMFocusIn, DOMFocusOut which are equivalents for IE's focusin and focusout events.

1
  • if (_is_ie) { // IE Only focus/blur event listeners f.observe('focusin', this.onFocus.bind(this)); f.observe('focusout', this.onBlur.bind(this)); } else { // Firefox & Safari focus/blur event listeners f.addEventListener('focus', this.onFocus.bind(this), true); f.addEventListener('blur', this.onBlur.bind(this), true); } Then inside onBlur and onFocus I get the element (Event.element) and check it's nodeName to see if i should do anything.
    – Louis W
    May 21, 2009 at 16:42
9

You can use this :

function focusInHandler(event){
    Event.element(event).fire("focus:in");
}
function focusOutHandler(event){
    Event.element(event).fire("focus:out");
}

if (document.addEventListener){
    document.addEventListener("focus", focusInHandler, true);
    document.addEventListener("blur", focusOutHandler, true);
} else {
    document.observe("focusin", focusInHandler);
    document.observe("focusout", focusOutHandler);
}

document.observe('focus:in', function(event) {
    // Your code
});

My jsFiddle : http://jsfiddle.net/EpokK/k7RPE/3/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.