项目作者: fed

项目描述 :
Simple modal focus trap implementation
高级语言: TypeScript
项目地址: git://github.com/fed/modal-focus-trap.git
创建时间: 2019-10-19T14:03:48Z
项目社区:https://github.com/fed/modal-focus-trap

开源协议:

下载


modal-focus-trap

Build Status
Downloads
Version
License

This is a very simple and lightweight helper function that makes it easier to set up a focus trap in a modal window. This implementation is not library specific and can therefore be used with VanillaJS, React or any other library/framework.

How to use

First import the helper function. You don’t necessarily need to name it focusTrap, you can use any name you want.

  1. import focusTrap from 'modal-focus-trap';

Set up the focus trap by passing in an HTMLElement which is your modal element. The function returns a callback you can use later on to disengage the focus trap. Cache this callback somewhere in your code, you will need it later.

  1. const modalElement = document.querySelector('.modal');
  2. let restoreFocus = focusTrap(modalElement);

After closing the modal, you need to disengage the focus trap and restore the focus to the previously focused element by invoking the callback:

  1. if (restoreFocus) {
  2. restoreFocus();
  3. restoreFocus = null;
  4. }

Using with React

You can also create a hook to use this helper with React:

  1. import { useRef, useEffect } from 'react';
  2. import focusTrap from 'modal-focus-trap';
  3. export default function useFocusTrap() {
  4. const ref = useRef(null);
  5. // Create on didMount.
  6. useEffect(() => {
  7. const destroy = focusTrap(ref.current);
  8. // Destroy on willUnmount.
  9. return destroy;
  10. }, []);
  11. return ref;
  12. }

See this sample project for more info.