Attribute actions
Dynamically modify HTML attributes with various triggers
Overview
This utility allows you to dynamically modify HTML attributes using various triggers like hover
or click
. You can add
, remove
, toggle
, or replace
attribute values without writing complex JavaScript, enabling more flexible and interactive behaviors for your elements.
Attribute actions let you control the attributes of HTML elements directly using triggers. The utility supports several actions:
- Add: Adds a value to the specified attribute.
- Remove: Removes a value or the entire attribute.
- Toggle: Toggles a specific value on and off.
- Replace: Replaces an existing value with a new one.
This feature simplifies dynamic attribute management, making it easy to customize element behavior in response to user interactions.
Syntax
trigger
: The interaction that triggers the action (e.g.,hover
,click
).action
: The desired action (add
,remove
,toggle
,replace
).attribute
: Specifies the target attribute name and value.name
: The attribute name (required).value
: The attribute value (optional, depending on the action).
Examples
These examples show how to dynamically modify HTML attributes using triggers like click
or hover
(you can use any of the supported triggers). Actions such as add
, remove
, toggle
, and replace
let you control attribute behavior to create interactive elements efficiently.
add
The add action appends a specified value
to an attribute. If the attribute already exists, the value is added to it without removing any existing values.
<!-- Add a "Peter" value to `data-name` attribute on hover -->
remove
The remove action deletes a specified value
from an attribute. If the value is part of a list (e.g., space-separated values), only that value is removed.
Remove whole attribute
The entire attribute, including all its values, can be removed by omitting the value
field.
toggle
The toggle action alternates a specified value
on or off within an attribute defined by the name
option. If the value exists, it is removed; if it doesn’t exist, it is added.
<!-- Toggle a "Peter" value on `data-name` attribute on hover -->
replace
The replace action swaps the existing value of an attribute with a new one. If the attribute already has the specified value, it is updated to the new value provided.