Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger onBlur on multiple elements as a single unit

I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.

I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.

Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.

Any suggestions on how to achieve this?

EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).

like image 814
Zecrates Avatar asked Nov 09 '11 14:11

Zecrates


2 Answers

I made a working example here: https://jsfiddle.net/bs38V/5/

It uses this:

$('#t1, #t2').blur(function(){
    setTimeout(function(){
        if(!$('#t1, #t2').is(':focus')){
            alert('all good');
        }
    },10);
});
like image 59
AndersDaniel Avatar answered Sep 29 '22 04:09

AndersDaniel


var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
    focus--;
    setTimeout(function() {
        if (!focus) {
            // both lost focus
        }
    }, 50);
});
like image 40
lanzz Avatar answered Sep 29 '22 05:09

lanzz