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

1

3 Answers 3

8

you can do it by

if ($("#id").is(":focus")) {
  alert('focus');
}
Sign up to request clarification or add additional context in comments.

3 Comments

$('#title').focusout(function() { if($("#MakeTicket/title").is(":focus")) { alert('focus'); } else { alert('not focus'); } $('#Department').focus(); return false; });
$('#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
Doesn't work for dynamic elements added to the DOM after runtime...
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

2 Comments

$('#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
I cant understand ur code here please post an edit in ur question. This will make ur code more readable.
1

You can use document.activeElement.

2 Comments

I have tried with this, but this will also not work
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, which is reasonably new so some browsers do not support it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.