Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why is the focus visible when a lightDom element in a web component is clicked? #1046

Open
Garcia-Christophe opened this issue Jan 24, 2024 · 0 comments

Comments

@Garcia-Christophe
Copy link

I've created a simple web component that lets you create a custom button.

When clicked, I want the page title to be focused.

With button tag and a simple text content inside, the title is not visually focused. Same with my web component (in slot). That's cool.

With button tag and a tag span inside, the title is not visually focused. But, the title is visually focused with my web component (in slot). That's not cool.

I don't understand why the title is visually focused (which I don't want it to be), when I click on the lightDom element (e.g. the span). This doesn't happen when I click on my component directly (the shadowDOM part).

I expect my title to be focus but not visible-focus, without hiding by forcing.

I tried to look at this thread too: Why is focus-visible applied on page load

// Template web component
const template = document.createElement('template');
template.innerHTML = `
      <style>
        button {
          background-color: lightgreen;
          padding: 10px;
        }
      </style>
      <button>
        <slot></slot>
      </button>`;

// Class web component
class MyBtn extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({
      mode: 'open'
    });

    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

// web component definition
window.customElements.define('my-btn', MyBtn);

// Set focus to title on click
function focusTitle() {
  const h1 = document.getElementById('title');
  h1.setAttribute('tabindex', -1);
  h1.focus();
}

// Add click event listener
document.getElementById('btn1').addEventListener('click', focusTitle);
document.getElementById('btn2').addEventListener('click', focusTitle);
<h1 id="title">Test redirection focus</h1>
<button id="btn1" style="padding: 10px">
    <span>(button > span) Click me and I don't visually focus title</span>
    (button > simple text content) Click me and I don't visually focus title
</button>

<my-btn id="btn2">
  <span>(MyBtn > span) Click me and I DO visually focus title</span>
  (MyBtn > simple text content) Click me and I don't visually focus title
</my-btn>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant