Why doesn't focus() select my container div?
make sure the element you want to focus has an attribute tabindex="-1"
, otherwise that element is not focusable.
For example
<div id="myfocusablediv" tabindex="-1"></div>
When you set the tabindex=-1 for an element it allows it to get focus() through javascript. If instead you want it to get focus through tabbing through elements, then you would set the tabindex attribute to 0.
Here's what I do when I want to force a certain form element to have focus:
function setFocusFixed( elm ){
if( !input ) return;
var savedTabIndex = elm.getAttribute('tabindex')
elm.setAttribute('tabindex', '-1')
elm.focus()
elm.setAttribute('tabindex', savedTabIndex)
}
// DEMO:
var buttons = document.querySelectorAll('button'),
input = document.querySelector('input');
buttons[0].addEventListener('click', ()=>input.focus())
buttons[1].addEventListener('click', ()=>setFocusFixed(input))
<input placeholder='some input' tabindex='2' />
<button>Set focus on input</button>
<button>Set focus on input - fixed</button>
This little function simply sets the form field tabindex
to -1
so the DOM focus()
method could take affect, and immediately sets it back to its original value.
Update Aug 2019:
Seems that on Chrome 76 giving focus works as it should, without the -1
tabindex
trick.
Once you submit the form, any focus becomes irrelevant. The document changes location to the form's action and the focus is lost anyway.
Looks like you want to set focus after the submit, in this case do it in the onload event:
window.onload = function WindowLoad(evt) {
byId("nav_container").focus();
}
As mentioned by others, if "nav_container" is not input box it won't work either and to scroll to that position use named anchor instead.. add such anchor before the element:
<a name="nav_container_anchor" />
Then have such JS code to scroll to that location:
document.location = "#nav_container_anchor";