Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to know when a table row loses focus?

Tags:

jquery

focus

In a table row (<tr>) there are several input elements.

I need to execute some JavaScript code when the tr loses focus (but not when the user just switches to a different input element in the same tr).

I use jQuery.

How to do it cross-browser?

like image 911
porton Avatar asked Dec 08 '22 15:12

porton


1 Answers

I suppose you're looking for this approach (demo, checked in Chr/Ff/IE10):

var delayedFn, blurredFrom;
$('tr').on('blur', 'input', function(event) {
    blurredFrom = event.delegateTarget;
    delayedFn = setTimeout(function() {
        console.log('Blurred');
    }, 0);
});
$('tr').on('focus', 'input', function(event) {
    if (blurredFrom === event.delegateTarget) {
        clearTimeout(delayedFn);
    }
});

As you see we delay the call to our "true blur handler" (which is the function with console.log in this example) with setTimeout - and clear this timeout if we see the focus stayed in the same row.

I use delegation here so I won't need to call closest(tr) each time. But it has another side-effect here, as the handler will deal correctly with the inputs added to the table dynamically.

like image 171
raina77ow Avatar answered Dec 28 '22 20:12

raina77ow