views:

301

answers:

3

What I wanted to do is figure out whenever the user is engaged with an INPUT or TEXTAREA element and set a variable flag to true... and set that flag to false immediately after the user is no longer engaged with them (ie. they've clicked out of the INPUT/TEXTAREA elements).

I used jQuery's docuemnt.ready function to add the onclick attribute to my body element and assign it to my getActive() function.

The code for the getActive() function is as follows:

function getActive()
{
  activeObj = document.activeElement;
  var inFocus = false;
  if (activeObj.tagName == "INPUT" || activeObj.tagName == "TEXTAREA")
  {
     inFocus = true;
  }
}

I'd really like to keep by project withing the jQuery framework, but can't seem to find a way of accomplishing the same logic above using JUST jQuery syntax.

A: 

Iis the .blur() event what you're looking for?

chryss
+2  A: 

You want the focus and blur event handlers. For example...

var inFocus = false;
$('input, textarea').focus(function() {
  inFocus = true;
});

$('input, textarea').blur(function() {
  inFocus = false;
});

I'm pretty sure that a comma will get you input OR textarea, but you get the idea if that doesn't pan out

Rob
I put this in, but it doesn't seem to get called when a user starts typing into the INPUT or TEXTAREA element.
Chrys G.
As an addendum to the point above, I'm fairly new to JavaScript and jQuery... I didn't realize that using those functions OUTSIDE the document.ready function would have JS bind those events to essentially non-existent elements as the DOM has not yet loaded.
Chrys G.
A: 

You can do something like this :

var focusItem = null; 
$('input, textarea').focus( function() { 
    focusItem = this; 
});
Soufiane Hassou
Just to clarify, 'focusItem' would then represent the INPUT or TEXTAREA DOM Object?
Chrys G.
it would represent to one who's focused regardless of his type. So it can be either an INPUT or a TEXTAREA
Soufiane Hassou