how to trap focus on button javascript code example

Example: javascript trap focus

/**
*Function should be called on keyPress or something
*/
function _focusTrapperEvent(e) {
  if (!(e.key === 'Tab' || e.keyCode === 9))
    return;
  let condition = 'a[href], area[href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object:not([disabled]), embed, *[tabindex], *[contenteditable]',
      first = $('.focusKeeper').find(condition).filter(':not(.select-element):visible:not(.invisible):first'),
      last = $('.focusKeeper').find(condition).filter(':not(.select-element):visible:not(.invisible):last');

  console.log(first);
  console.log(last);

  if ( e.shiftKey ) /* shift + tab */ {
    if (document.activeElement === first[0]) {
      last[0].focus();
      e.preventDefault();
    }
  } else /* tab */ {
    if (document.activeElement === last[0]) {
      first[0].focus();
      e.preventDefault();
    }
  }
}