Willem van der Veen
Willem van der Veen

Reputation: 36680

data-* attributes in HTML5

was reading an article on Mozilla about data attributes. The article says that you can use data-* attributes to store extra information regarding the element. For example:

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

Question:

Is their sole purpose to add custom metadata to an HTML element or are there other use cases?

Upvotes: 1

Views: 100

Answers (1)

Joel
Joel

Reputation: 6211

An example of how to create and use custom attrs with Angular as framework (to demonstrate the usecase)

HTML:

<button id="monitorBtn-{{machine.id}}">
     <span ng-show="!$ctrl.isMonitored(machine)">
         StackOverFlow
     </span>
</button>

JS:

var element = angular.element("#monitorBtn-"+machine.id);
element.attr("tooltip","Your Tooltip Text"); // <-- setting custom attr
element.attr("flow","up");
console.log(element);

This will append an attribute to the button-class like this:

<button id="monitorBtn-{{machine.id}}" tooltip="Your tooltip Text" flow="up" ....>

of course: this custom-class is generated with CSS4.

CSS:

:root {
    --bg: #05a8ff;
    --dink: 7px;
}

[tooltip] {
    position: relative;
}
[tooltip]:not([flow])::after,
[tooltip][flow^="up"]::after {
    bottom: calc(100% + var(--dink));
}

This is in no way an answer to the question, and I don't think there is a real answer to this question. It's pretty broad, but i'll post this code to give you an idea of the usecase for how data-* attrs could work in different languages, and why HTML is embracing them.

Upvotes: 2

Related Questions