Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make focus on the html element using jquery

Tags:

html

jquery

how to make focus on the html element using jquery

like image 499
binesh Avatar asked Mar 18 '11 11:03

binesh


People also ask

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.

How do you set focus on a specific element in HTML?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

What is focus function in jQuery?

jQuery focus() Method The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.

What is focus () in JavaScript?

JavaScript | Focus() JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.


2 Answers

I hope you found the issue 6 years ago, but if you are testing the focus function with the console tool opened on the current Firefox and Chrome, it may prevent the focus event from firing properly.

In order to test it, you can setTimeout and close the developer tool before it fires.

For example:

setTimeout(focusAtMyElement, 3000);

function focusAtMyElement(){
    $('#my-element').focus();
}

By any means I am not recommending setTimeout for production code, this is for "visual testing purposes" only so you can close the dev tool on the browser before the focus event fires and you can see the expected result.

like image 189
Rafael Fernandes Avatar answered Sep 28 '22 01:09

Rafael Fernandes


Pretty easy.

$('#itemId').focus();
like image 23
Dutchie432 Avatar answered Sep 27 '22 23:09

Dutchie432