Label
Renders an accessible label associated with controls.
TailwindCSS
Vanilla JS
package showcase
import "github.com/axzilla/templui/components"
templ CheckboxWithLabel() {
<div class="flex items-center gap-2">
@components.Checkbox(components.CheckboxProps{
ID: "checkbox-with-label",
})
@components.Label(components.LabelProps{
For: "checkbox-with-label",
}) {
Accept terms and conditions
}
</div>
}
package components
import "github.com/axzilla/templui/utils"
type LabelProps struct {
ID string
Class string
Attributes templ.Attributes
For string
Error string
}
templ Label(props ...LabelProps) {
{{ var p LabelProps }}
if len(props) > 0 {
{{ p = props[0] }}
}
<label
if p.ID != "" {
id={ p.ID }
}
if p.For != "" {
for={ p.For }
}
class={
utils.TwMerge(
"text-sm font-medium leading-none inline-block",
utils.If(len(p.Error) > 0, "text-destructive"),
p.Class,
),
}
data-disabled-style="opacity-50 cursor-not-allowed"
{ p.Attributes... }
>
{ children... }
</label>
}
templ LabelScript() {
{{ handle := templ.NewOnceHandle() }}
@handle.Once() {
<script defer nonce={ templ.GetNonce(ctx) }>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('label[for]').forEach(function(label) {
// Disabled style handler
function updateLabelStyle(label) {
const forId = label.getAttribute('for');
const targetElement = document.getElementById(forId);
if (targetElement && targetElement.disabled) {
// Retrieve the custom disabled style or use the default
const disabledStyle = label.getAttribute('data-disabled-style');
disabledStyle.split(' ').forEach(function(className) {
if (className) {
label.classList.add(className);
}
});
} else {
// Remove the disabled style
const disabledStyle = label.getAttribute('data-disabled-style');
disabledStyle.split(' ').forEach(function(className) {
if (className) {
label.classList.remove(className);
}
});
}
}
// Update the initial style
updateLabelStyle(label);
// Create a MutationObserver for this specific label
const forId = label.getAttribute('for');
const targetElement = document.getElementById(forId);
if (targetElement) {
const observer = new MutationObserver(function() {
updateLabelStyle(label);
});
observer.observe(targetElement, {
attributes: true,
attributeFilter: ['disabled']
});
}
});
});
</script>
}
}