Trap Focus Inside an Element

Focus means a center of activity, attraction or attention. When it comes to computer or browser, focus means the active element ready to take input or execute events. That could be the cursor in a text field or an active button or hyperlink inside wrapper element.

Focus trapping means not letting the focus go out of some element.

Keyboard Tab or Shift + Tab is used to move the focus to next or previous focusable element. The current active element is called the focus element and the previous element from where the focus shifted is called the blurred element.

Generally we do not notice focus or blur while using the mouse pointer. But that becomes very useful when we use keyboard.

In certain scenarios we need a focus trap.

Sometime some specific area of a page is emphasized and we do not want the user to access other elements. For example a lightbox. Specific HTML content or Image is loaded inside a lightbox in the same page. Everything works well except the focus.

When the tab or shift tab key is pressed the focus moves through all the focusable elements in the web page and managing a lightbox with keyboard becomes very difficult. So we need trap the focus inside the emphasized element.

To overcome this situation we won’t allow the focus go outside the emphasized element. So the logic is to loop the focus. There may be many focusable elements inside the emphasized element.

We will just need two “keydown” events, first one is to be registered to the first focusable element the second one is to be registered to the last focusable element.

When shift + tab key is pressed while first focusable element is active, we’ll move the focus to the last focusable element. And when tab key is pressed while last focusable element is active, we’ll move the focus to the first focusable element using JavaScript.

Use below code in jQuery

jQuery(document).ready(function () {

    jQuery('#lastElementId').on('keydown', function (e) {

        var isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);

        if (!isTabPressed) {
            return;
        }

        if (e.shiftKey) /* shift + tab */ {
            return;
        } else /* tab */ {
            jQuery('#firstElementId').focus();
            e.preventDefault();
        }

    });

    jQuery('#firstElementId').on('keydown', function (e) {

        var isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);

        if (!isTabPressed) {
            return;
        }

        if (e.shiftKey) /* shift + tab */ {
            jQuery('#lastElementId').focus();
            e.preventDefault();
        } else /* tab */ {
            return;
        }

    });
});

Hope this helps.

Share this Post