views:

158

answers:

2

I want a certain function to be called when neither of two inputs on the page has focus. If the user merely switches from one input to the other, I do not want the function to be called. Any ideas?

A: 

Try this:

<input type="text" Id="Text1" onfocus="InTextbox()" onblur="OutOfTextBox()"/>
<input type="text" id="Text2" onfocus="InTextbox()" onblur="OutOfTextBox()"/>


<script>
var inTextBox=false;
function InTextBox()
{
    inTextBox=true;
}
function OutOfTextBox()
{
    inTextBox=false;
}

function YourFunction()
{
   if(inTextBox) return; //one of the textboxes has focus so return
   .......
}
</script>

variable inTextBox is set true when a textbox gets focused and set to false when it loses focus.

TheVillageIdiot
You're not invoking anything in event handler. Shouldn't that be - `onfocus="InTextbox()"`? Also, why capitalized name for something that's not a constructor (or namespace)?
kangax
this won't work in the use case where the user switches focus directly from one text box to the other
Ben McCann
+1  A: 

try this (edited):

<input type="text" onfocus="doFocus(1)" onblur="doBlur(1)"/>
<input type="text" onfocus="doFocus(2)" onblur="doBlur(2)"/>

<script>
var fstate=[]; // focus state
fstate[1] = false;
fstate[2] = false;

function doit() { alert('lost focus'); }

function doBlur(i) {
  fstate[i]=false;
  // give some time to the other element to receive focus
  // because the onblur event gets fired before the onfocus
  setTimeout("if (!fstate[1] && !fstate[2]) doit();",50);  
}

function doFocus(i) { fstate[i]=true; }
</script>
Pedro Ladaria
This is basically what I was thinking as well. I was hoping there was a way to avoid setTimeout as it seemed a bit hackish, but it's the only solution I've been able to come up with thus far.
Ben McCann