Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element that has focus on it with jQuery

How can you select an element that has current focus?

There is no :focus filter in jQuery, that is why we can use something like this:

$('input:focus').someFunction(); 
like image 484
jQuery Lover Avatar asked Feb 05 '09 14:02

jQuery Lover


People also ask

How do I target a specific element in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do you focus an element in jQuery?

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.

Is Focus deprecated in jQuery?

focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.

How do you know if input has focus?

To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input. to check if the input element is focused.


2 Answers

alert($("*:focus").attr("id")); 

I use jQuery.

It will alert id of element is focusing.

I hope it useful for you.

like image 28
BiBi Avatar answered Sep 16 '22 20:09

BiBi


$(document.activeElement) will return the currently focused element and is faster than using the pseudo selector :focus.

Source: http://api.jquery.com/focus-selector/

like image 134
Sam Shiles Avatar answered Sep 18 '22 20:09

Sam Shiles