Reputation: 213
how to make focus on the html element using jquery
Upvotes: 14
Views: 21886
Reputation: 503
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.
Upvotes: 4
Reputation: 21
you can focus either by element type, its id or its class. for example create a button.
> <button id="id" class="class1">
now to make the focus on this button you can follow these methods: 1. by the button itself. note :- in case of multiple button it will focus on the last button.
$("button").focus();
$(".class1").focus();
by its id(use '#' before id)
$("#id").focus();
even by button followed by its class name
$("button.class1").focus();
Upvotes: 2
Reputation: 6647
<input class="element_class" type="text"/>
<input id="element_id" type="text"/>
<script>
$('.element_class').focus();
// the following will obviously blur() the previous
$('#element_id').focus();
</script>
focus documentation
blur documentation
Upvotes: 1
Reputation: 1927
HTML:
<form>
<input id="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
<div id="other">
Trigger the handler
</div>
FOCUS EXAMPLES
$('#target').focus(function() {
alert('Handler for .focus() called.');
});
$('#other').click(function() {
$('#target').focus();
});
Upvotes: 0