I have been searching and have not found any particular thread that addresses my issue.
I am trying to either write an event listener or a conditional action with JavaScript that reacts when a user selects the TAB key and shifts focus to the appropriate element on screen.
Current DIV id has focus on screen => id="Slide14549accStr2" When the user selects the TAB key, I want the user's focus to immediately shift to DIV id "Titleinformation_tb". I am unable to change the TabIndex in the HTML to do this the normal way, so I am left with using javascript in some form.
Here is what I have so far.
document.getElementById('Slide14549accStr2').addEventListener('keydown') {
if event.keyCode == 9) {
var elem =
document.getElementById('Titleinformation_tb');
$(elem).focus();
};
I would appreciate any help and feedback.
I have been searching and have not found any particular thread that addresses my issue.
I am trying to either write an event listener or a conditional action with JavaScript that reacts when a user selects the TAB key and shifts focus to the appropriate element on screen.
Current DIV id has focus on screen => id="Slide14549accStr2" When the user selects the TAB key, I want the user's focus to immediately shift to DIV id "Titleinformation_tb". I am unable to change the TabIndex in the HTML to do this the normal way, so I am left with using javascript in some form.
Here is what I have so far.
document.getElementById('Slide14549accStr2').addEventListener('keydown') {
if event.keyCode == 9) {
var elem =
document.getElementById('Titleinformation_tb');
$(elem).focus();
};
I would appreciate any help and feedback.
Share Improve this question edited Aug 22, 2017 at 17:02 brk 50.4k10 gold badges59 silver badges83 bronze badges asked Aug 22, 2017 at 16:56 Agent OrangeAgent Orange 211 gold badge1 silver badge2 bronze badges 1-
If you can't change the
tabindex
in the HTML, why not change it via JavaScript? Can I dynamically set tabindex in JavaScript? – yuriy636 Commented Aug 22, 2017 at 17:01
2 Answers
Reset to default 4If you just fix all the syntax errors, it works just fine, but you should be preventing the default action as well, to make sure it doesn't tab to the next element
document.getElementById('Slide14549accStr2').addEventListener('keydown', function(event) {
if (event.keyCode == 9) {
event.preventDefault();
var elem = document.getElementById('Titleinformation_tb');
elem.focus();
}
});
<input id="Slide14549accStr2" placeholder="Focus this, and tab out">
<br><br><br>
<input><input><input>
<br><br><br>
<input id="Titleinformation_tb" placeholder="Should go here">
You were missing the function call.
document.getElementById('Slide14549accStr2')
.addEventListener('keydown',function(e){
if (event.keyCode == 9){
var elem = document.getElementById('Titleinformation_tb');
$(elem).focus();
}
});