Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Focus() function not working

Tags:

javascript

I have a textbox which I want to set the focus on, but it doesn't work.

document.getElementById("txtCity").focus();

Any idea?

like image 821
Itay.B Avatar asked Jan 25 '11 20:01

Itay.B


3 Answers

Maybe you are calling the JavaScript before the input element is rendered? Position the input element before the JavaScript or wait until the page is loaded before you trigger your JavaScript.

In that order, it works just fine:

<input type="text" id="test" />
<script type="text/javascript">
  document.getElementById("test").focus();
</script>

In jQuery you could place your code within the .ready() method to execute your code first when the DOM is fully loaded:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    $("#test").focus();
    // document.getElementById("test").focus();
  });
</script>
like image 59
Martin Buberl Avatar answered Nov 08 '22 09:11

Martin Buberl


I have also faced same problem.To resolve this problem, put your code in setTimeout function.

function showMeOnClick() {
    // Set text filed focus after some delay
    setTimeout(function() { jQuery('#searchTF').focus() }, 20);
    // Do your work.....
}
like image 24
Rubi saini Avatar answered Nov 08 '22 11:11

Rubi saini


In case someone searching has a similar situation to mine ... I had to set a tabindex attribute before my div could receive focus():

featured.setAttribute('tabindex', '0');
featured.focus();
console.log(document.activeElement===featured); // true

(I found my answer here: Make div element receive focus )

And of course, make sure the body element is ready before setting focus to a child element.

like image 9
Symbolic Avatar answered Nov 08 '22 10:11

Symbolic