4

I'm trying to make a safari extension that does something if the cursor focus isn't in a text field. However the following code to detect if the focus isn't in a text field does not work.

    if ($(document.activeElement).attr("type") != "text" 
       && $(document.activeElement).attr("type") != "textarea") {
          ..do something
    }
thisiscrazy4
  • 1,905
  • 8
  • 35
  • 58
  • Duplicate: http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus – WilHall Apr 27 '12 at 02:01
  • `textarea` isn't a `type` attribute value - it is a tag name. You probably meant to check `document.activeElement.localName == "textarea"` (yes, sometimes things are simpler without jQuery). – Wladimir Palant Apr 27 '12 at 06:08
  • `localName` isn't implemented in IE 8 or lower. Better (compatible with more browsers) to use `tagName.toLowerCase() == 'textarea'` – RobG Apr 27 '12 at 06:34

3 Answers3

15

Just keep it simple:

var el = document.activeElement;

if (el && (el.tagName.toLowerCase() == 'input' && el.type == 'text' ||
    el.tagName.toLowerCase() == 'textarea')) {
  // focused element is a text input or textarea
} 
RobG
  • 142,382
  • 31
  • 172
  • 209
1

You can use jquery to achive this

$('input[type="text"]').focus(function() {
   alert('Focused');
});
Dips
  • 3,220
  • 3
  • 20
  • 21
-2
$("input[type=text]").filter(":not(:focus)").css("background","#ff0000");

$("input[type=text]").focus(function(){
    $(this).css("background","#ffffff");
});

$("input[type=text]").blur(function(){
    $(this).css("background","#ff0000");
});

Should set all the non-active inputs' background to red. (Worked in Chrome 18)

Goldentoa11
  • 1,700
  • 2
  • 17
  • 29