1

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.

brk
  • 48,835
  • 10
  • 56
  • 78
Agent Orange
  • 11
  • 1
  • 1
  • 2
  • If you can't change the `tabindex` in the HTML, why not change it via JavaScript? [Can I dynamically set tabindex in JavaScript?](https://stackoverflow.com/questions/3772438/can-i-dynamically-set-tabindex-in-javascript) – yuriy636 Aug 22 '17 at 17:01

2 Answers2

4

If 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">
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

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();
 }
});
Mohhamad Hasham
  • 1,750
  • 1
  • 15
  • 18