SuperNinja
SuperNinja

Reputation: 1596

JQuery updating data- attribute

Consider the following example of a photo album.

The first page and last page of the album are half the size of the spread of the album. I set the attr('data-width') and attr('data-width_correct') for comparison

For Example -- checkImageDimesions()

//Define if first or last page
if($(this).is(':first-child') || $(this).is(':last-child'))
{
    $(this).find('img').attr('data-height_correct' , maxHeight);
    $(this).find('img').attr('data-width_correct' , maxWidth / 2);  
} else{
    $(this).find('img').attr('data-height_correct' , maxHeight);
    $(this).find('img').attr('data-width_correct' , maxWidth);  
} 

This works as expected, updating the data- with the correct values. My next step is if the width > width_correct I want to add a class of resize.

if($(this).find('img').data('width') > $(this).find('img').data('width_correct'))
{

     $(this).addClass('resize');
}

The calling of this function happens on the success of jQuery .sortable(). On first sort this works correctly, however on subsequent sorts, the initial image that is not sized correctly retains the .resize and any new image that would return false on width > width_correctdoes not get assigned resize

Sortable

$("#sortable").sortable(
{
success: function(){checkImageDimension()} 
}

Upvotes: 2

Views: 2175

Answers (2)

mate64
mate64

Reputation: 10072

Attaching object data (something that's not a simple string, number, or boolean) to a DOM node will often cause memory leaks in Internet Explorer. That's because DOM nodes are not native Javascript objects in IE, so it doesn't understand how to garbage collect things that are attached to them.

If you just need a simple flag or number on a DOM node you can use either attr("x_mycount", 1) or just set a property on the DOM node using this.x_mycount instead. (Be careful choosing the attribute or property name since you're in the DOM namespace and you could clobber something if you're not careful.) It's safest to use .data() though.

Source: forum.jquery.com/topic/when-to-use-attr-vs-data

Upvotes: 1

jefffan24
jefffan24

Reputation: 1326

To update data attributes you just add a second parameter to the data function.

$('#elementID').data('width-correct', '400');

That's it, and it will update.

Upvotes: 0

Related Questions