HTML <picture> data-* Attribute

The data-* attribute on a <picture> tag attaches additional data to the picture. To create a custom attribute, replace the * with a lowercase string, such as data-id, data-status, or data-location.

Example

#

A custom data-title attribute on a <picture> tag.
The attribute value is not visible, but it is readable by JavaScript.

Vincent Van Gogh
<picture data-title="Portrait of Vincent Van Gogh">
  <source media="(max-width: 520px)" srcset="/img/html/vangogh-sm.jpg">
  <source media="(max-width: 768px)" srcset="/img/html/vangogh.jpg">
  <img src="/img/html/vangogh-lg.jpg" alt="Vincent Van Gogh">
</picture>

Using data-*

The data-* attribute adds custom information to a <picture> element.

The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.

An <picture> 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 picture.


Syntax

<picture data-*="value">

Note: The * can be any string, such as data-iddata-costdata-supplier,  etc.


Values

#

Value Description
value A string value. Can be numeric, alphanumeric, JSON, etc.

More Examples

A custom data-topic attribute on a <picture> tag.
Clicking the button will display the topic value.

Vincent Van Gogh

<picture id="mypicture" data-topic="Self portrait by Vincent Van Gogh">
  <source media="(max-width: 520px)" srcset="/img/html/vangogh-sm.jpg">
  <source media="(max-width: 768px)" srcset="/img/html/vangogh.jpg">
  <img src="/img/html/vangogh-lg.jpg" alt="Vincent Van Gogh">
</picture>

<br/><br/>
<button onclick="show();">Show data</button>

<script>
  let show = () => {
    let element = document.getElementById("mypicture");
    alert("Topic = " + element.getAttribute('data-topic'));
  }
</script>

Code explanation

The <picture> tag has a custom data-topic attribute.

The topic of the picture is stored in the data-topic.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the picture topic.

Note: Notice how the title displays immediately without server call.


Browser support

Here is when data-* support started for each browser:

Chrome
38.0 Oct 2014
Firefox
38.0 May 2015
IE/Edge
13.0 Nov 2015
Opera
25.0 Oct 2014
Safari
9.1 Mar 2016

You may also like

 Back to <picture>
Guides