Data attribute changes not detected with jQuery
Asked Answered
C

2

5

I am changing the data-demo attribute of a div element and when I want to check it with in another event, it always shows me the initial value of it instead of the current value.

This is the code I am using:

$('#showValue').click(function(){
    alert($('.value').data('demo'));
});

$('.update').click(function(){
   $('.value').text('updated').attr('data-demo', 'updated');
});

Why is this happening?

Here's a fiddle with the example I am talking about: http://jsfiddle.net/f5Cpm/

Thanks.

Cohbert answered 2/5, 2013 at 12:38 Comment(0)
F
6

The jQuery .data() functions aren't truly supporting the HTML5 dataset functionality, but rather load in all the html5 dataset data into their own data collection. In consequence updates to the dataset by changing the attribute are not reflected in the jQuery internal data collection.

In other words, you either need to consequently use dataset.demo, $().data("demo") or $().attr("data-demo"). The advantage of the second being that it cross browser of course and part of jQuery if you're using jquery for the rest of the application.

Forthcoming answered 2/5, 2013 at 12:43 Comment(0)
S
9

After the internal data is first initialized, it never goes back to the attribute to get or set the value, therefore updating the attribute will not update what is stored in .data() if you've already used .data on that element.

Read more here

Solace answered 2/5, 2013 at 12:41 Comment(0)
F
6

The jQuery .data() functions aren't truly supporting the HTML5 dataset functionality, but rather load in all the html5 dataset data into their own data collection. In consequence updates to the dataset by changing the attribute are not reflected in the jQuery internal data collection.

In other words, you either need to consequently use dataset.demo, $().data("demo") or $().attr("data-demo"). The advantage of the second being that it cross browser of course and part of jQuery if you're using jquery for the rest of the application.

Forthcoming answered 2/5, 2013 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.