Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code to detect if focus is in a text field

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
    }
like image 570
thisiscrazy4 Avatar asked Dec 12 '22 03:12

thisiscrazy4


2 Answers

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
} 
like image 65
RobG Avatar answered Jan 11 '23 20:01

RobG


You can use jquery to achive this

$('input[type="text"]').focus(function() {
   alert('Focused');
});
like image 33
Dips Avatar answered Jan 11 '23 19:01

Dips