Makuhari Development Corporation
2 min read, 279 words, last updated: 2021/12/1
TwitterLinkedInFacebookEmail

Keep Focusing an Element

Sometimes we want to keep the focused element continue to be focused after clicking some other buttons.

Based on the Web Accessibility requirements, we may consider this a special feature only needed for certain input fields/elements when necessary.

This leads us to think about event.relatedTarget. We can use it to find out if the next focused element is suspicious.

Notice that sometimes the element could be nested, and could be focused on different levels, we could use both matches and querySelectorAll to ensure us to find it out.

/**
 * Check if is/contain the node based on the selector
 * @param e focus event
 * @param selector the string selector
 * @returns contains or not
 */
export const isContainSelection = (
  e: React.FocusEvent<HTMLElement>,
  selector: string
): boolean => {
  return (
    e.relatedTarget !== null &&
    (e.relatedTarget.querySelectorAll(selector).length > 0 ||
      e.relatedTarget.matches(selector))
  );
};

We can use data-* the global attributes to help our identification.

Now we can update our blur handler to achieve this feature!

export default function App() {
  const inputRef = useRef<HTMLInputElement>(null);
  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    if (isContainSelection(e, "[data-keep-focus-input]")) {
      console.log("let's keep focus!");
      inputRef!.current!.focus();
    } else {
      // do something else normally
    }
  };
  return (
    <div className="App">
      <input onBlur={handleBlur} ref={inputRef} />
      <button>button</button>
      <button data-keep-focus-input>button keeps focus</button>
    </div>
  );
}

Since we are not doing anything tricky mutating the handler itself, we can still write our customized logic inside the onBlur handler to approach real-world requirements later, for example

  • nesting with multiple conditions for the focus control
  • manually control the input cursor pointer position back to the input once lost focused on certain elements
Makuhari Development Corporation
法人番号: 6040001134259
サイトマップ
ご利用にあたって
個人情報保護方針
個人情報取扱に関する同意事項
お問い合わせ
Copyright© Makuhari Development Corporation. All Rights Reserved.