Question

I see a lot of Html tags these days with attributes that start with data- as in the following example.

<button type="button" class="btn" data-dismiss="modal" aria-hidden="true" ng-click="closeClippingModal();">Cancel</button>

My question is simply this. Why is this used?

Was it helpful?

Solution 2

Most common use is storing data for javascript. As an example lets say you have a photo and you want to display it on webpage with hover efect being location and time of image taken. The simpliest way of storing data asociated with element is to use data-* attribute on the element:

<img src="my/awesome/photo.jpg" data-location="Paris, France" data-datetime="30.3.2014 16:19:00" />

It's as simple as that.

OTHER TIPS

It is an html5 attribute meant to store things like meta data or other data associated with the element. It's commonly used to store state in JavaScript applications.

You can easily access it using JQuery like so $("#myElement").data("dismiss");

The data-* attributes is used to store custom data private to the page or application, gives us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

data-* attributes consist of two parts:

  1. The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
  2. The attribute value can be any string

Note: Custom attributes prefixed with "data-" will be completely ignored by the user agent.

This feature is described quite well in John Resig’s blog.

Simply, the specification for custom data attributes states that any attribute that starts with “data-” will be treated as a storage area for private data (private in the sense that the end user can’t see it – it doesn’t affect layout or presentation).

This allows you to write valid HTML markup (passing an HTML 5 validator) while, simultaneously, embedding data within your page

One of reasons is storing data instead of class. This is more semantic way. Data-attributes is the HTML5 novation. Also you can easily access them through JS (dataset) and jQuery (data() method). For more information see the specification: http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"

As I know data-attribut's name can contain uppercase letters but these letters will be forcibly converted in lowercase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top