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

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 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

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 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

    The best CRM software with email marketing in 2025: Expert tested and reviewed

    July 22, 2025
    News & Updates

    This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

    July 22, 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

    CVE-2025-40726 – Nosto Reflected Cross-Site Scripting (XSS)

    Common Vulnerabilities and Exposures (CVEs)

    This Prime Day deal nets you 21% off a powerful mini-PC that supports desktop-class GPUs — it’s been my daily driver for months

    News & Updates

    Adobe’s brand refresh

    Web Development

    Marktechpost Releases 2025 Agentic AI and AI Agents Report: A Technical Landscape of AI Agents and Agentic AI

    Machine Learning

    Highlights

    Helldivers 2 is coming to Xbox Series X|S this August with full crossplay

    July 4, 2025

    In a surprise move, Helldivers 2 is officially heading to Xbox. Once a major PlayStation…

    How do you check for the equivalent of ‘deceptive design’ for coding in software?

    April 4, 2025

    NVIDIA’s laptop GPUs are being throttled — modder blows past limits with 250W RTX 5090 and unlocks 40% more performance

    July 22, 2025

    CVE-2025-0853 – WordPress PGS Core Plugin SQL Injection Vulnerability

    May 6, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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