7

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?

CharlesX
  • 418
  • 4
  • 7
  • 14

1 Answers1

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');" />

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.

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
  • `$("*").focus()`, I guess? –  Aug 31 '17 at 12:53
  • 10
    The 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