In HTML5, it has data-* attribute which is used to store custom data with an HTML element. These attributes used to keep more information on HTML elements. When we access these elements from javascript, the adequate information stored will make our work easy.
We are going see an example to read HTML5 data-* attribute via jQuery. In this example a HTML <img> tag has data-* attributes. We are reading these attributes to perform zoom-in and zoom out operations.
This code contains two data attributes, data-action, and data-imgname. data-action is used to store the action (zoom-in, zoom out) to be performed. And the data-imgname is used to store the name of the image name to be shown after zoom operations.
The code is,
<img class="demo-image" src="photo_thumbnail.jpg"
title="Zoom In"
data-action="zoom-in"
data-imgname="photo_enlarge.jpg" />
We are accessing data-action attribute from jQuery. Based on the data-action value the zoom in and zoom out will happen. During these operations, we are using data-imgname value to change the image. The script is,
<script type="text/javascript">
$(".demo-image").click( function() {
var currentImage = $(this).attr("src");
var action = $(this).data("action");
$(this).attr("src", $(this).data("imgname"));
$(this).data("imgname", currentImage);
if(action=="zoom-in") {
$(this).attr("title","Zoom Out");
$(this).data("action","zoom-out");
$(this).css("cursor", "-webkit-zoom-out");
} else {
$(this).attr("title","Zoom In");
$(this).data("action","zoom-in");
$(this).css("cursor", "-webkit-zoom-in");
}
});
</script>