Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to set focus programmatically does not work with Firefox

I have a problem in Firefox trying to set the focus to a control using jqueryjavascript. While my specific problem is quite involved, even the simple test case below does not work for me. The input is found, its value is changed but the input is not focused.
Issue present with Firefox only

Tried with Firefox 44.0.2 on Windows 7
It works as it should with MS IE 10 and Chrome

$().ready(function() {
  $("#I").val(3);
  $("#I").focus(); // JQuery focus - does not work
  
  var ctl = document.getElementById('I')
  ctl.value='DOM';
  ctl.focus(); // DOM Native focus - does not work
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type=text id=I>
like image 412
edc65 Avatar asked Mar 17 '26 16:03

edc65


2 Answers

This style of ready event:

$().ready(function() {

Long ago deprecated and better not to use it.


You can use autofocus attribute:

$(document).ready(function() {
  $('#I').val(3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=I autofocus>

and instead of jQuery's try triggerring the DOM .focus() event:

$(document).ready(function() {
  $('#I').val(3);
  $('#I')[0].focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=I>
like image 167
Jai Avatar answered Mar 20 '26 08:03

Jai


I believe there is an issue with setting focus on Firefox, there is a workaround which involves using focusout. See below:

$().ready(function() {

    $('#I').val(3);

    $('#I').focusout(function() {
        setTimeout(function() {
            $(this).focus();
        }, 0);
    });

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

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="I" />
like image 42
Donal Avatar answered Mar 20 '26 08:03

Donal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!