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
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).
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.
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.
To detect if an element has focus, you compare it with the document. activeElement .
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With