I have some buttons styled with TailwindCSS.
These buttons contains some icons / helper text (<span>
) that should receive a color (different than the color used for button text) when the mouse is over the button.
I used the group
class on button, and then in the inner element:
<script src="https://cdn.tailwindcss.com#.js"></script>
<button class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed">
<span class="group-hover:text-pink-900">helper text</span>
</button>
<button disabled class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed">
<span class="group-hover:text-pink-900">helper text</span>
</button>
Notifce that the hover effect is set only when the button is enabled (by using hover:enabled
).
If the button is disabled, I want to disable this hover effect on the helper text well.
I've tried group-hover:enabled:text-pink-900
, but it does not work.
disabled:pointer-events-none
is not an option for me, because it will break disabled:cursor-not-allowed
.
Answers
To achieve the desired behavior where the hover effect is applied only when the button is enabled and disabled when the button is disabled, you can use JavaScript to conditionally apply the styles to the helper text based on the button's disabled state.
Here's how you can do it:
<script src="https://cdn.tailwindcss.com#.js"></script>
<button id="button" class="group bg-indigo-500 hover:enabled:bg-indigo-400 disabled:cursor-not-allowed">
<span id="helper-text" class="group-hover:text-pink-900">helper text</span>
</button>
<script>
const button = document.getElementById('button');
const helperText = document.getElementById('helper-text');
button.addEventListener('mouseenter', () => {
if (!button.disabled) {
helperText.classList.add('text-pink-900');
}
});
button.addEventListener('mouseleave', () => {
if (!button.disabled) {
helperText.classList.remove('text-pink-900');
}
});
</script>
In this script, we're using JavaScript to add and remove the text-pink-900
class from the helper text element (<span>
) based on the button's disabled
state. When the mouse enters the button area (mouseenter
event), the helper text's color is changed to pink only if the button is enabled. Similarly, when the mouse leaves the button area (mouseleave
event), the helper text's color is reverted back to its original color if the button is enabled. If the button is disabled, the hover effect on the helper text will not be applied.