How to detect a changed focus event in JS?

I want to write a function, this function can determine if the focus is on a specific element. If the focus is on the element, I call the function onfocus(), and if not on the element, I do nothing. How can i do this?

+4
source share
1 answer

Many different ways to do this.

Here are two examples:

Solution No. 1:

You can use a simple built-in function onblurto find out if this particular element is focused. This is probably the easiest way to do this.

<input type="text" onblur="javascript:alert('You have focused out');" />

Demo

Solution No. 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 a few, you can use:

$('input, textarea, select').focus(function() {

Loans

blur focus, , .

+7

Source: https://habr.com/ru/post/1547681/


All Articles