Read HTML5 Data Attribute via jQuery

by Vincy. Last modified on July 12th, 2022.

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.

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.

jquery-image-zooming

The code is,

<img class="demo-image" src="photo_thumbnail.jpg" 
	title="Zoom In" 
	data-action="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).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>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page