The last example of jQuery\'s focus() documentation states
$(\'#id\').focus()
should make the input focused (active). I can\'t seem to get
if you use bootstrap + modal, this worked for me :
$(myModal).modal('toggle');
$(myModal).on('shown.bs.modal', function() {
$('#modalSearchBox').focus()
});
Make sure the element and its parents are visible. You cannot use focus on hidden elements
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.
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.
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?
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);
}