Reputation: 12704
The last example of jQuery's focus()
documentation states
$('#id').focus()
should make the input focused (active). I can't seem to get this working.
Even in the console on this site, I'm trying it for the search box
$('input[name="q"]').focus()
and I'm getting nothing. Any ideas?
Upvotes: 214
Views: 270778
Reputation: 7781
focus
for unfocused element)Same for jquery
-or- vanilla js
.
focus()
work only if the element
can be focused.
focusable
(By default) - for example: a, button, input
not focusable
(By default) - for example: div, li, section, h1
So if you try to set focus
for h1
you need to set tabindex.
$("h1").focus();
<h1 tabindex="0">Focus</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
focus
after click on button
or a
)Same for jquery
-or- vanilla js
.
"The Problem" - button
-or- a
focus after click. So you need to blur()
the button and only than change focus.
$( "[open_modal]" ).on( "click", function(event) {
this.blur();
$("[modal]").attr('tabindex', '-1');
$("[modal]").focus();
} );
*:focus{
outline: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<a href="#" open_modal>focus modal</a>
<div modal>hello modal</div>
tabindex="-1"
- means that the element is not reachable via sequential keyboard navigation. But still can be focus by javascript
(For example off-screen modal
).
$( "[open_modal]" ).on( "click", function() {
$("[modal]").attr('tabindex', '-1');
document.querySelector('[modal]').focus();
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<li href="#" open_modal>focus modal</li>
<div modal>hello modal</div>
Upvotes: 0
Reputation: 1130
In case jquery wont work, you can easily make it work with vanilla js:
setTimeout(function() { document.querySelector("#id").focus() }, 500);
Upvotes: 2
Reputation: 9
As this is a little old, ive added a current solution. if you need to tab focus to the next input use $("#elid").nextAll("input")[0].focus(). Occassionally you'll need to use a timout function to delay but 200ms should suffice full example:
$(document).on("keyup", "#Advert input", function (e) {
let el = $(e.target).closest("input")
if (e.which == 13) {
$(el).nextAll("input")[0].focus()
}
})
Upvotes: -1
Reputation: 3415
Using .keypress()
was the issue for me.
Try using .keyup()
or .input()
if you are too.
.keydown()
has odd behaviour. It moves the input to the new focus field.
Upvotes: 0
Reputation: 1734
Setting tabindex=0 before focus() helped me
const $elOk = $modal.querySelector('.modal__button-ok');
$elOk.setAttribute('tabindex', '0');
$elOk.focus();
Upvotes: 0
Reputation: 8910
Some of the answers here suggest using setTimeout
to delay the process of focusing on the target element. One of them mentions that the target is inside a modal dialog. I cannot comment further on the correctness of the setTimeout
solution without knowing the specific details of where it was used.
The simple fact of the matter is that you cannot focus on an element which is not yet visible. If you run into this problem ensure that the target is actually visible when the attempt to focus it is made. In my own case I was doing something along these lines:
$('#elementid').animate({left:0,duration:'slow'});
$('#elementid').focus();
This did not work. I only realized what was going on when I executed $('#elementid').focus()` from the console which did work. The difference - in my code above the target there is no certainty that the target will infact be visible since the animation may not be complete. And there lies the clue:
$('#elementid').animate({left:0,duration:'slow',complete:focusFunction});
function focusFunction(){$('#elementid').focus();}
works just as expected. I too had initially put in a setTimeout
solution and it worked too. However, an arbitrarily chosen timeout is bound to break the solution sooner or later depending on how slowly the host device goes about the process of ensuring that the target element is visible.
Upvotes: 27
Reputation: 251
I faced a similar issue and wrapping the event within setTimout
function worked perfectly for me.
But somehow it felt like this wasn't the best approach to resolve it (manually delaying the event).
However, In my case the focus event wasn't triggering as the element was invisible/hidden and it turns out that the element was visible after a few milliseconds as I was triggering the focus event within element.on("focus")
function (which is a triggered when the element is clicked and the element is focused in).
This worked for me:
element.on("focus", (e) => {
e.preventDefault();
if (element.is(":visible")) {
search_input.trigger("focus");
}
});
Upvotes: 1
Reputation: 1416
You can try this id
is tries
window.location.hash = '#tries';
Upvotes: 1
Reputation: 31
In my case, and in case someone else runs into this, I load a form for view, user clicks "Edit" and ajax gets & returns values and updates the form.
Just after this, I tried all of these and none worked except:
setTimeout(function() { $('input[name="q"]').focus() }, 3000);
which I had to change to (due to ajax):
setTimeout(function() { $('input[name="q"]').focus() }, **500**);
and I finally just used $("#q") even though it was an input:
setTimeout(function () { $("#q").focus() }, 500);
Upvotes: 3
Reputation: 11
I tested code from Chrome's DevTool Console and the focus part not worked. I found out later the issue is only present if i run it from DevTool and if i implement the code to the website it works fine. Actually, the element got focused but the DevTool removed it immediately.
Upvotes: 0
Reputation: 1125
Pro tip. If you want to turn on focus from the dev console then just open the console as a separate window from the options tab. The latest Firefox and Chrome supports this feature.
Upvotes: 0
Reputation: 786
Make sure the element and its parents are visible. You cannot use focus on hidden elements
Upvotes: 1
Reputation: 5276
Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.
Upvotes: 4
Reputation: 4963
For my case I had to specify a tab index (-1
if only focusable via script)
<div tabindex='-1'>
<!-- ... -->
</div>
Upvotes: -1
Reputation: 4242
Add a delay before focus(). 200 ms is enough
function focusAndCursor(selector){
var input = $(selector);
setTimeout(function() {
// this focus on last character if input isn't empty
tmp = input.val(); input.focus().val("").blur().focus().val(tmp);
}, 200);
}
Upvotes: 4
Reputation: 492
For those with the problem of not working because you used "$(element).show()". I solved it the next way:
var textbox = $("#otherOption");
textbox.show("fast", function () {
textbox[0].focus();
});
So you dont need a timer, it will execute after the show method is completed.
Upvotes: 2
Reputation: 4867
Just in case anybody else stumbles across this question and had the same situation I had - I was trying to set the focus after clicking on another element, yet the focus didn't appear to work. It turns out I just needed an e.preventDefault();
- here's an example:
$('#recipients ul li').mousedown(function(e) {
// add recipient to list
...
// focus back onto the input
$('#message_recipient_input').focus();
// prevent the focus from leaving
e.preventDefault();
});
This helped:
If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement. Source: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/focus
Upvotes: 13
Reputation: 504
I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.
I was using ng-repeat
for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.
so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>
That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function
I hope this helps.
Upvotes: 5
Reputation: 2725
if you use bootstrap + modal, this worked for me :
$(myModal).modal('toggle');
$(myModal).on('shown.bs.modal', function() {
$('#modalSearchBox').focus()
});
Upvotes: 26
Reputation: 1435
ADDITIONAL SOLUTION Had same issue where focus() didn't seem to work but eventually it turned out that what was needed was scrolling to the correct position:
Upvotes: -2
Reputation: 49
I realize this is old, but came across it today. None of the answers worked for me, what I did find that worked was setTimeout. I wanted my focus to be placed on the input filed of a modal, using the setTimeout worked. Hope this helps!
Upvotes: 4
Reputation: 1440
Found a solution elsewhere on the net...
$('#id').focus();
did not work.
$('#id').get(0).focus();
did work.
Upvotes: 88
Reputation: 10239
Actually the example you gave for focusing on this site works just fine, as long as you're not focused in the console. The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box:
setTimeout(function() { $('input[name="q"]').focus() }, 3000);
As for your other one, the one thing that has given me trouble in the past is order of events. You cannot call focus() on an element that hasn't been attached to the DOM. Has the element you are trying to focus already been attached to the DOM?
Upvotes: 496