binesh
binesh

Reputation: 213

how to make focus on the html element using jquery

how to make focus on the html element using jquery

Upvotes: 14

Views: 21886

Answers (6)

Rafael Fernandes
Rafael Fernandes

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

Dutchie432
Dutchie432

Reputation: 29170

Pretty easy.

$('#itemId').focus();

Upvotes: 31

Sudesh Yadav
Sudesh Yadav

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();

  1. focus by class name(use '.' before class name)

$(".class1").focus();

  1. by its id(use '#' before id)

    $("#id").focus();

  2. even by button followed by its class name

$("button.class1").focus();

Upvotes: 2

acm
acm

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

Sbml
Sbml

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

Ed Fryed
Ed Fryed

Reputation: 2198

$("input").focus();

there you go!

Upvotes: 2

Related Questions