3

How to get input tag of html has focus or not using jquery

keydown event will work for form if input,image etc. tag has focus. but it will not work it focus is on form but not on any tags like input,image etc. How can I solve this. Please help Thanks in advance

$('#title').focusout(function() { if($(document.activeElement).is(":focus")) { alert('focus'); } else { alert('not focus'); } }); // this will not work

Royal Pinto
  • 2,869
  • 8
  • 27
  • 39

3 Answers3

8

you can do it by

if ($("#id").is(":focus")) {
  alert('focus');
}
chhameed
  • 4,406
  • 4
  • 26
  • 44
  • $('#title').focusout(function() { if($("#MakeTicket/title").is(":focus")) { alert('focus'); } else { alert('not focus'); } $('#Department').focus(); return false; }); – Royal Pinto Jul 15 '11 at 07:57
  • $('#title').focusout(function() { if($("#MakeTicket/title").is(":focus")) { alert('focus'); } else { alert('not focus'); } $('#Department').focus(); return false; }); but this will not work. anything wrong in my code – Royal Pinto Jul 15 '11 at 07:58
  • 1
    Doesn't work for dynamic elements added to the DOM after runtime... – Alex Jun 14 '12 at 21:53
3

Its much easier to check by using jquery. Using jquery u can do it like this

if($"#div/inputtocheck").is(":focus"))
{
//do something u want if it is in focus
}

The :focus returns true if the div is in foucs and false if it is not in focus

kritya
  • 3,312
  • 7
  • 43
  • 60
  • $('#title').focusout(function() { if($("#MakeTicket/title").is(":focus")) { alert('focus'); } else { alert('not focus'); } $('#Department').focus(); return false; }); but this will not work. anything wrong in my code – Royal Pinto Jul 15 '11 at 07:58
  • I cant understand ur code here please post an edit in ur question. This will make ur code more readable. – kritya Jul 15 '11 at 08:01
1

You can use document.activeElement.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • I have tried with this, but this will also not work – Royal Pinto Jul 15 '11 at 09:18
  • 1
    That is what jQuery uses, I suggested it because it's a lot more efficient to use than a jQuery object and selector. If you can't get it to work directly, then jQuery can't help. *document.activeElement* is part of the W3C [Element Traversal Specification](http://www.w3.org/TR/ElementTraversal/), which is reasonably new so some browsers do not support it. – RobG Jul 15 '11 at 23:44