':focus-within only works when focusing button with keyboard, not with click in Firefox 63
I have a field layout with an outer div (.field) and the label, input and a button inside that field. When I focus the input field, the :focus-within pseudo selector matches, so .field__inner gets an outer border color.
When I use tab to cycle through the elements, the :focus-within matches when I focus the input field or the button.
But when I click the button, :focus-within doesn't seem to 'trigger' (it works in Chrome though).
I've tried to add a tabindex attribute to the button, but that had no effect.
I am using Firefox 63 on macOS.
.field__inner {
border: 1px solid #000;
}
.field:focus-within .field__inner {
border: 1px solid #f00;
}
<div class="field">
<div class="field__inner">
<label for="password" class="field__label">
Name
</label>
<input type="text" class="field__input" value="">
<button class="field__passwordreveal" type="button">
Click this button!
</button>
</div>
</div>
How can I maintain :focus-within in Firefox when I click the button?
Edit: added animated gif to demonstrate the issue:
Solution 1:[1]
I retried this today in Firefox 98 on macOS, and it works as intended: the :focus-within fires when I click the button.
Time heals all wounds, and in this case it solved my problem!
Solution 2:[2]
This is happening for me as well but I found a clean workaround:
If you hook to the onclick event for either the parent (the one you select via :focus-within) or a child element, you can just retrieve the child element and force it to focus:
<div onclick="document.getElementById(#child).focus()">
<span id="child" />
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thijs Kramer |
| Solution 2 | Dharman |

