9

i have a div with data attribut like

<div class='p1' data-location='1'></div>

and i have script like

$('button').click(function(){

    var loc = $('.p1').data('location');
    alert('data location is'+loc);//SHOW THE DATA

    var num = 10;
    var count = loc;
    var element = $('.p1');
    var intv = setInterval(anim,1000); 
    function anim(){
        count++;
        num--;
        if(count==37){count = 1;}
        if(num==1){clearInterval(intv);}
        $(element).animateCSS('bounceOut',{
            callback: function(){
                $(element).attr('data-location',count);
                $(element).animateCSS('bounceIn');
            }
        });

    }
    anim();

});

with the script above the data-location attribute will be updated to 10, but if i click the button again, the data-location is still 1

Barmar
  • 669,327
  • 51
  • 454
  • 560
Mamen
  • 1,170
  • 4
  • 17
  • 38

3 Answers3

17

The first time that you use .data() to access a data-* attribute, the value of that attribute is cached internally by jQuery, and .data() uses the cache from then on. Updating the attribute with .attr() does not update the cache, you need to use .data() to update it. That's why you need to use

$(element).data('location', count);

to update it.

Barmar
  • 669,327
  • 51
  • 454
  • 560
3
        $(element).attr('data-location',count);

is different than

        $(element).data('location',count);

so, use the second instead.

Check Data vs Attr for details.

Community
  • 1
  • 1
Bardh Lohaj
  • 1,392
  • 1
  • 8
  • 17
3

you are setting the attr property and not data using .attr('data-location',count). to get the attribute you need to use .attr('data-location'):

var loc = $('.p1').attr('data-location');
Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120
  • I was having a similar issue because an item got the same id of an item that was deleted from the DOM but the cache still kept the old value. Using attr to access the value solved the problem – valepu Jun 11 '19 at 08:33