Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery focus on load

How to set the focus on a html element ?

I use document.getElementById('ID_HTML_wanted').focus(); but my html element "ID_HTML_wanted" as not the focus. I user jquery api .focus

like image 686
immobiluser Avatar asked Oct 18 '11 22:10

immobiluser


People also ask

How do you focus to the element on page load?

Using Window: load Event: The load event of window object is fired when the complete page has loaded including stylesheets and images. Now when the page has been loaded , we can use HTMLElement. focus() method to provide focus to our element(if can be focused).

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.

What is Focus event in JQuery?

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.

How do you know if input field has focus?

To detect if an element has focus, you compare it with the document. activeElement .


1 Answers

Try to wrap your code to this code so it executes AFTER DOM is ready

$(function(){
    //your code
});

so it will become

$(function(){
    document.getElementById('ID_HTML_wanted').focus();
});

However, your element't don't have .focus() method, if you want to REALLY use jQuery's one, use

$(function(){
    $("#ID_HTML_wanted").focus();
});
like image 197
genesis Avatar answered Sep 20 '22 11:09

genesis