Miva Merchant Modules and Development
Want to start an online store? We work with you from start to finish, from commerce platform to design to SEO.
Experience counts, and we have a lot.

JQUERY: Data Attribute Magic

Scot Ranney • January 12, 2024


Data attributes are the way to go when using jquery/js to pass data from an element via a click.

Example 1: Jquery, how the data attributes on click:

<a id="option1" data-id="10" data-option="21" href="#">
	   Click to do something
</a>

$('#option1').on('click', function () {
	var $el = $(this);	
	console.log($el.data('id'), $el.data('option'));
});

Example 2: Jquery, function to show data attributes on click.

<a id="option1" 
	   data-id="10" 
	   data-option="21" 
	   href="#" 
	   onclick="goDoSomething(this);">
	Click to do something
</a>

<script type="text/javascript">
	function goDoSomething(identifier){	 
		alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));			   
	}
</script>

Example 3: Straight up JS with a function:

<a id="option1" 
	   data-id="10" 
	   data-option="21" 
	   href="#" 
	   onclick="goDoSomething(this);">
	Click to do something
</a>
   
<script type="text/javascript">
	function goDoSomething(d){
		alert(d.getAttribute("data-id"));
	}
</script>

Changing Data Attributes on the Page

Data attributes are interesting because if you use them as data they will be in the memory/environment but not changed on the page.

To change them on the page adjust them as attributes attr

var a = $('#mydiv').data('data-thickness'); //getter

$('#mydiv').attr('data-thickness',20); //setter for attribute

$('#mydiv').data('data-thickness',20); //setter memory/environment

https://www.scotsscripts.com/mvblog/jquery-set-and-get-data-attributes.html

mvkb_jquery