Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delegate focus event? [duplicate]

Tags:

jquery

Possible Duplicate:
Focus and blur jQuery events not bubbling

var default_input_value = null;
jQuery('body').on('focus focusout', 'input[type="text"]', function(event){
    if(event.type === 'focus'){
        default_input_value = jQuery(this).val();
        jQuery(this).val('');
    }else if(event.type === 'focusout')
        if(jQuery(this).val().length === 0)
        jQuery(this).val(default_input_value);
    }
);

This code simply does not respond to the event. P.S. it is important that there would be input[type="text"], because jQuery focus also fires on checkbox in some situations....

like image 571
Kin Avatar asked Jan 24 '13 07:01

Kin


1 Answers

Under .on() jquery document, there is a description:

The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.

Hope this would be useful.

And you can try this code:

var default_input_value = null;
jQuery('body').on('focusin focusout', 'input[type="text"]', function(event){
    if(event.type === 'focusin'){
        default_input_value = jQuery(this).val();
        jQuery(this).val('');
    }else if(event.type === 'focusout'){
        if(jQuery(this).val().length === 0)
        jQuery(this).val(default_input_value);
    }
});
like image 147
pktangyue Avatar answered Nov 23 '22 18:11

pktangyue