Search code examples
javascripthtmlcssaccessibility

Why does my Shadow DOM button (tabindex="0") get focus after the regular button (tabindex="10") and how can I fix it?


I'm trying to ensure that a button inside a Shadow DOM gets tab focus before a regular button in the main DOM. one button have tabindex="0", and the other one is 10 but the regular button outside the shadow is always focused first.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        button{
            padding: 1%;
            border-radius: 10px;
            width: 100px;
            height: 50px;   
            
        }
        button:focus {
        background-color: red;
        }

    </style>
</head>
<body>
      
        <div id="shdow">
            
        </div>

        <button  tabindex="10">focus me </button>


        <script>
            // set shadow root with button taindex 0
            document.querySelector('#shdow').attachShadow({mode: 'open'}).innerHTML = `
                <style>
        button{
            padding: 1%;
            border-radius: 10px;
            width: 100px;
            height: 50px;   
            
        }
        button:focus {
        background-color: green;
        }

    </style>
            <button tabindex="0">focus me </button>`;

        </script>

</body>
</html>


Solution

  • The solution i found is to set the tab index onto the shadow root element then the next focus will be what comes inside