Read HTML5 Data Attribute via jQuery

In HTML5, it has data-* attribute which is used to store custom data with an HTML element. This 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.

View Demo


HTML Code with Data Attribute

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-imgname="photo_enlarge.jpg" />

jQuery Data Attribute Access

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).css("cursor", "-webkit-zoom-out");
		} else {
			$(this).attr("title","Zoom In");
			$(this).css("cursor", "-webkit-zoom-in");

View DemoDownload

This jQuery code tutorial was published on March 6, 2016.

↑ Back to Top