简体   繁体   中英

JavaScript - JQuery - focus() method - infinite loop

I'm trying to build a functionality that allows keyboard tabbing between two buttons (CodePen below). More specifically I would like the user to be able to tab onto "button1" and on tab, jump to "button2" and then on tab jump back to button 1.

My solution is to put an event listener on "button1" and listen for a tab keyboard event. When that is triggered, use JQuery's focus() method to shift focus to "button2". On "button2" there is an identical listener that listens for tab event and shift focus back to "button1".

The problem is that when I tab onto "button1", the listener records focus and tab event and shift focus onto "button2" which in turn records focus and tab event and shift it back to "button1" again, creating an infinite loop.

Could I please get suggestions in how to solve this problem?

The real world application of this would be to restrict tabbing within a specific module or section of a page.

Thanks! Steve

https://codepen.io/steveliu7/pen/WOoMJY

var $button1 = $('.b1');
var $button2 = $('.b2');

var checkButton = function(event) {
 if ($button1.is(':focus') && event.which === 9){
  console.log($(this))
  $('.b2').focus();
   return;
 };

 if ($button2.is(':focus') && event.which === 9){
  console.log($(this))
  $('.b1').focus();
   return;
 };
}

$('button').on('keydown', checkButton);

I think what you are trying to do can be achieved much easier with the tabindex property in HTML. If you want to restrict tabbing to certain elements only, you can set tabindex="-1" for those elements that you do not want focused.

Source: https://www.w3schools.com/tags/att_global_tabindex.asp

You want to restrict tab navigation between two buttons.

Note that it won't restrict screenreaders navigation to those two buttons.

You have to consider TAB navigation but also SHIFT+TAB navigation

On a purely technical point of view event.preventDefault() is what your are searching for:

var checkButton = function(event) {
  if (event.which === 9) {
    if ($button1.is(':focus')) {
      $button2.focus();
      event.preventDefault();
    } else if ($button2.is(':focus')){
      $button1.focus();
      event.preventDefault();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM