A data-* attribute on a <button> tag attaches additional data to the button.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-productid
attribute on a button.
The attribute value is not visible, but is readable by JavaScript.
<button data-productid="12247"
onclick="alert('Product added!');">
<img src="/img/html/cart.png"> Add to Cart
</button>
The data-* attribute adds custom information to a <button> element.
The * part is replaced with a lowercase string, such as data-id, data-type, data-inventory, etc.
A <button> element can have any number of data-* attributes, each with their own name.
Using data-* attributes reduces the need for requests to the server.
Note: The data-* attribute is not visible and does not change the appearance of the button.
<button data-*="value" >
Note: The * can be any string, such as data-id
, data-cost
, data-supplier
, etc.
Value | Description |
---|---|
value | A string value. Can be numeric, alphanumeric, JSON, etc. |
Four different custom data-* attributes on a <button>.
Clicking the button will display all their values.
<button data-id="49982"
data-color="black"
data-size="9"
data-product="Nike shoes"
onclick="addToCart(this);">
<img src="/img/html/cart.png"> Add to Cart
</button>
<script>
let addToCart = button => {
let s = "Id = " + button.getAttribute('data-id') + "\r\n";
s += "Color = " + button.getAttribute('data-color') + "\r\n";
s += "Size = " + button.getAttribute('data-size') + "\r\n";
s += "Product = " + button.getAttribute('data-product');
alert(s);
}
</script>
The <button> tag has four data-* attributes.
They are data-id
, data-color
, data-size
, and data-product
.
Button clicks are directed to the onclick
event.
Onclick invokes a JavaScript function that extracts and displays all four values.
Here is when data-* support started for each browser:
Chrome
|
1.0 | Sep 2008 |
Firefox
|
1.0 | Sep 2002 |
IE/Edge
|
1.0 | Aug 1995 |
Opera
|
1.0 | Jan 2006 |
Safari
|
1.0 | Jan 2003 |
Back to <button>