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?
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?
- 1 See here developer.mozilla/en-US/docs/Web/API/document.activeElement – elclanrs Commented Jul 9, 2014 at 2:09
- OK,let me hava a check – CharlesX Commented Jul 9, 2014 at 2:10
-
I use thie like
var curElement = document.activeElement;
but when I check thecurElement
, it returns undefined. – CharlesX Commented Jul 9, 2014 at 2:14 - possible duplicate of How can I get query string values in JavaScript? – CharlesX Commented Sep 11, 2014 at 13:15
1 Answer
Reset to default 9Many 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="alert('You have focused out');" />
Demo
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");
});
});
Demo
If you want multiple, you could use:
$('input, textarea, select').focus(function() {
Credits
You could use blur
and focus
functions to see if that certain element is focused.