I'm trying to reset data attributes after an animation and am running through some trouble applying the technique from answer 2 of this post.
Not sure what I'm missing here. Seems theoretically feasible to say for each
data
attribute, etc.
UPDATE:
Worth mentioning that the data
keys are all different. E.g. data-1="abc"
, data-2="abc"
, etc, hence the need for a for
loop that simply looks for data
attributes.
HTML
var total = 0;
$.each($('*').data(), function(key, value) {
if (key){
var thiis = $(this);
total += key;
thiis.removeData();
thiis.data(total, value);
}
});
Boom, got it. The script has a lot of overhead, so running it in an instance that a user will wait through isn't an option, IMO. You could improve it with specificity instead of the *
selector.
JavaScript (jQuery):
var counter = 1; // not necessary for your implementation, using it to adjust numeric data keys
$('*').each(function(){ // query all selectors and run through a loop
var thiis = $(this),
dataAttr = thiis.data(),
i;
if (dataAttr) { // if the element has data (regardless of attribute)
var newAttrs = []; // for the element's new data values
$.each(dataAttr, function(key, value) { // loop through each data object
var newKey = key + counter, // calculate new data key
newAttr = [newKey, value]; // push the new data set
newAttrs.push(newAttr); // push to elements new attributes array
thiis
.removeData(key) // remove the data
.removeAttr('data-' + key); // remvoe the attribute (unnecessary)
});
for (i = 0; i < newAttrs.length; i++) { // for each new attribute
thiis.data(newAttrs[i][0], newAttrs[i][1]); // add the data
thiis.attr('data-' + newAttrs[i][0], newAttrs[i][1]); // add the attribute (unnecessary)
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With