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?
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');" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With