Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect focus changed event in JS?

Tags:

javascript

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?

like image 683
CharlesX Avatar asked Jul 09 '14 02:07

CharlesX


1 Answers

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.

like image 182
imbondbaby Avatar answered Sep 20 '22 02:09

imbondbaby