I want to write a function, this function can detect whether the focus is on the certain element.If the focus is on the element, I call the onfocus()
function, and if not on the element, I do nothing.How can I do this?
Asked
Active
Viewed 3.3k times
7

CharlesX
- 418
- 4
- 7
- 14
-
1See here https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement – elclanrs Jul 09 '14 at 02:09
-
OK,let me hava a check – CharlesX Jul 09 '14 at 02:10
-
I use thie like `var curElement = document.activeElement;` but when I check the `curElement`, it returns undefined. – CharlesX Jul 09 '14 at 02:14
-
possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – CharlesX Sep 11 '14 at 13:15
1 Answers
8
Many different ways to do this.
Here is 2 examples:
Solution #1:
You could use simple inline onblur
function to see if that certain element is focused out. This is probably the simplest way to do it.
<input type="text" onblur="javascript:alert('You have focused out');" />
Solution #2:
HTML:
<input type="text" />
JQuery:
var selectedInput = null;
$(function() {
$('input').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
alert("You have focused out");
});
});
If you want multiple, you could use:
$('input, textarea, select').focus(function() {
You could use blur
and focus
functions to see if that certain element is focused.

Community
- 1
- 1

imbondbaby
- 6,351
- 3
- 21
- 54
-
Yeah, this is good, but when I leave this element and on another element, I can not know I am not on the `text` element. Right? – CharlesX Jul 09 '14 at 02:18
-
When you leave the element, it should detect that you left the element because of the `onblur` inline function :) – imbondbaby Jul 09 '14 at 02:19
-
Oh, sorry, the `onblur` attribute is what I said, thank you very much~ – CharlesX Jul 09 '14 at 02:20
-
-
10The whole JavaScript scene on StackOverflow is just ruined. Unless someone defines explicitly that they want JQuery, then JavaScript means just that -- clean JavaScript. Frameworks come and go, and since people somehow imagine replying with jQuery explicit code is OK -- StackOverflow is swamped with hundreds of thousands of replies like this, where you mistake a framework for a language or platform! – Jon Lennart Aasenden Aug 16 '20 at 03:05