How do I check if a data-attribute changes? [duplicate]
First of all the data- attribute - while you can access the data attribute using .attr or .prop, data is stored in an object $.cache
on page load and manipulated thereafter. The attributes data-* are NEVER updated.
To set data
$el.data('id', max.cid);
To get data
var something = $el.data('id');
Unfortunately there is no way to listen for a change in data without using setInterval as previously explored in this similar question.
That said, if it's only YOUR code that's updating the data, a logical solution is this:
Set up an event
$el.on('datachange', function(){ // procedure here});
Then either trigger it when you update the data
$el.data('id', max.cid).trigger('datachange');
or write your own data function that uses .data() and triggers the event
$.fn.mydata=function(key, variable){ $(this).data(key, variable).trigger('datachange');}$el.mydata('id', max.cid);
Example: http://jsfiddle.net/Qn9H6/
$("#test").on('datachange', function(e, key){ $('#feedback').hide().text('data "' + key + '" was changed to ' + $(this).data(key)).fadeIn(1000);});$.fn.mydata=function(key, variable){ if ($(this).data(key)!=variable){ // check if it's changed $(this).data(key, variable).trigger('datachange', key); }else{ console.log('data wasn\'t changed'); }}$('button').click(function() { $("#test").mydata('id', $(this).text());})$("#test").mydata('id', 456);