Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      Beyond the benchmarks: Understanding the coding personalities of different LLMs

      September 5, 2025

      Top 10 Use Cases of Vibe Coding in Large-Scale Node.js Applications

      September 3, 2025

      Building smarter interactions with MCP elicitation: From clunky tool calls to seamless user experiences

      September 4, 2025

      From Zero to MCP: Simplifying AI Integrations with xmcp

      September 4, 2025

      Distribution Release: Linux Mint 22.2

      September 4, 2025

      Coded Smorgasbord: Basically, a Smorgasbord

      September 4, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Drupal 11’s AI Features: What They Actually Mean for Your Team

      September 5, 2025
      Recent

      Drupal 11’s AI Features: What They Actually Mean for Your Team

      September 5, 2025

      Why Data Governance Matters More Than Ever in 2025?

      September 5, 2025

      Perficient Included in the IDC Market Glance for Digital Business Professional Services, 3Q25

      September 5, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      How DevOps Teams Are Redefining Reliability with NixOS and OSTree-Powered Linux

      September 5, 2025
      Recent

      How DevOps Teams Are Redefining Reliability with NixOS and OSTree-Powered Linux

      September 5, 2025

      Distribution Release: Linux Mint 22.2

      September 4, 2025

      ‘Cronos: The New Dawn’ was by far my favorite experience at Gamescom 2025 — Bloober might have cooked an Xbox / PC horror masterpiece

      September 4, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»News & Updates»A Primer on Focus Trapping

    A Primer on Focus Trapping

    July 21, 2025

    Focus trapping is a term that refers to managing focus within an element, such that focus always stays within it:

    • If a user tries to tab out from the last element, we return focus to the first one.
    • If the user tries to Shift + Tab out of the first element, we return focus back to the last one.

    This whole focus trap thing is used to create accessible modal dialogs since it’s a whole ‘nother trouble to inert everything else — but you don’t need it anymore if you’re building modals with the dialog API (assuming you do it right).

    Anyway, back to focus trapping.

    The whole process sounds simple in theory, but it can quite difficult to build in practice, mostly because of the numerous parts to you got to manage.

    Simple and easy focus trapping with Splendid Labz

    If you are not averse to using code built by others, you might want to consider this snippet with the code I’ve created in Splendid Labz.

    The basic idea is:

    1. We detect all focusable elements within an element.
    2. We manage focus with a keydown event listener.
    import { getFocusableElements, trapFocus } from '@splendidlabz/utils/dom'
    
    const dialog = document.querySelector('dialog')
    
    // Get all focusable content
    const focusables = getFocusableElements(node)
    
    // Traps focus within the dialog
    dialog.addEventListener('keydown', event => {
      trapFocus({ event, focusables })
    })

    The above code snippet makes focus trapping extremely easy.

    But, since you’re reading this, I’m sure you wanna know the details that go within each of these functions. Perhaps you wanna build your own, or learn what’s going on. Either way, both are cool — so let’s dive into it.

    Selecting all focusable elements

    I did research when I wrote about this some time ago. It seems like you could only focus an a handful of elements:

    • a
    • button
    • input
    • textarea
    • select
    • details
    • iframe
    • embed
    • object
    • summary
    • dialog
    • audio[controls]
    • video[controls]
    • [contenteditable]
    • [tabindex]

    So, the first step in getFocusableElements is to search for all focusable elements within a container:

    export function getFocusableElements(container = document.body ) {
    
      return {
        get all () {
          const elements = Array.from(
            container.querySelectorAll(
              `a,
                button,
                input,
                textarea,
                select,
                details,
                iframe,
                embed,
                object,
                summary,
                dialog,
                audio[controls],
                video[controls],
                [contenteditable],
                [tabindex]
              `,
            ),
          )
        }
      }
    }

    Next, we want to filter away elements that are disabled, hidden or set with display: none, since they cannot be focused on. We can do this with a simple filter function.

    export function getFocusableElements(container = document.body ) {
    
      return {
        get all () {
          // ...
          return elements.filter(el => {
            if (el.hasAttribute('disabled')) return false
            if (el.hasAttribute('hidden')) return false
            if (window.getComputedStyle(el).display === 'none') return false
            return true
          })
        }
      }
    }

    Next, since we want to trap keyboard focus, it’s only natural to retrieve a list of keyboard-only focusable elements. We can do that easily too. We only need to remove all tabindex values that are less than 0.

    export function getFocusableElements(container = document.body ) {
      return {
        get all () { /* ... */ },
        get keyboardOnly() {
          return this.all.filter(el => el.tabIndex > -1)
        }
      }
    }

    Now, remember that there are two things we need to do for focus trapping:

    • If a user tries to tab out from the last element, we return focus to the first one.
    • If the user tries to Shift + Tab out of the first element, we return focus back to the last one.

    This means we need to be able to find the first focusable item and the last focusable item. Luckily, we can add first and last getters to retrieve these elements easily inside getFocusableElements.

    In this case, since we’re dealing with keyboard elements, we can grab the first and last items from keyboardOnly:

    export function getFocusableElements(container = document.body ) {
      return {
        // ...
        get first() { return this.keyboardOnly[0] },
        get last() { return this.keyboardOnly[0] },
      }
    }

    We have everything we need — next is to implement the focus trapping functionality.

    How to trap focus

    First, we need to detect a keyboard event. We can do this easily with addEventListener:

    const container = document.querySelector('.some-element')
    container.addEventListener('keydown', event => {/* ... */})

    We need to check if the user is:

    • Pressing tab (without Shift)
    • Pressing tab (with Shift)

    Splendid Labz has convenient functions to detect these as well:

    import { isTab, isShiftTab } from '@splendidlabz/utils/dom'
    
    // ...
    container.addEventListener('keydown', event => {
      if (isTab(event)) // Handle Tab
      if (isShiftTab(event)) // Handle Shift Tab
      /* ... */
    })

    Of course, in the spirit of learning, let’s figure out how to write the code from scratch:

    • You can use event.key to detect whether the Tab key is being pressed.
    • You can use event.shiftKey to detect if the Shift key is being pressed

    Combine these two, you will be able to write your own isTab and isShiftTab functions:

    export function isTab(event) {
      return !event.shiftKey && event.key === 'Tab'
    }
    
    export function isShiftTab(event) {
      return event.shiftKey && event.key === 'Tab'
    }

    Since we’re only handling the Tab key, we can use an early return statement to skip the handling of other keys.

    container.addEventListener('keydown', event => {
      if (event.key !== 'Tab') return
    
      if (isTab(event)) // Handle Tab
      if (isShiftTab(event)) // Handle Shift Tab
      /* ... */
    })

    We have almost everything we need now. The only thing is to know where the current focused element is at — so we can decide whether to trap focus or allow the default focus action to proceed.

    We can do this with document.activeElement.

    Going back to the steps:

    • Shift focus if user Tab on the last item
    • Shift focus if the user Shift + Tab on the first item

    Naturally, you can tell that we need to check whether document.activeElement is the first or last focusable item.

    container.addEventListener('keydown', event => {
      // ...
      const focusables = getFocusableElements(container)
      const first = focusables.first
      const last = focusables.last
    
      if (document.activeElement === last && isTab(event)) {
        // Shift focus to the first item
      }
    
      if (document.activeElement === first && isShiftTab(event)) {
        // Shift focus to the last item
      }
    })

    The final step is to use focus to bring focus to the item.

    container.addEventListener('keydown', event => {
      // ...
    
      if (document.activeElement === last && isTab(event)) {
        first.focus()
      }
    
      if (document.activeElement === first && isShiftTab(event)) {
        last.focus()
      }
    })

    That’s it! Pretty simple if you go through the sequence step-by-step, isn’t it?

    Final callout to Splendid Labz

    As I resolve myself to stop teaching (so much) and begin building applications, I find myself needing many common components, utilities, even styles.

    Since I have the capability to build things for myself, (plus the fact that I’m super particular when it comes to good DX), I’ve decided to gather these things I find or build into a couple of easy-to-use libraries.

    Just sharing these with you in hopes that they will help speed up your development workflow.

    Thanks for reading my shameless plug. All the best for whatever you decide to code!


    A Primer on Focus Trapping originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleModules in Terraform: Creating Reusable Infrastructure Code
    Next Article Reek – examines Ruby classes, modules, and methods

    Related Posts

    News & Updates

    Building smarter interactions with MCP elicitation: From clunky tool calls to seamless user experiences

    September 4, 2025
    News & Updates

    From Zero to MCP: Simplifying AI Integrations with xmcp

    September 4, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    RAIDOU Remastered: The Mystery of the Soulless Army Review (PC) – A well-done action-RPG remaster that makes me hopeful for more revivals of classic Atlus titles

    News & Updates

    Set up an AI-powered Laravel Development Environment with Claude Code and MCP Servers

    Development

    The world’s smallest 65W USB-C charger is my latest travel essential

    News & Updates

    Whisp, a Pure PHP SSH server, with Ashley Hindle

    Development

    Highlights

    Call for Speakers – JS Conf Armenia 2025

    August 30, 2025

    Comments Source: Read More 

    The UX Research Revolution Is Already Here

    August 13, 2025

    20+ Best Free InDesign Brochure Templates for Creatives in 2025

    May 20, 2025

    Deno 2.4: deno bundle is back

    July 8, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.