Reputation: 521
I've got some variables that I need to pass in jQuery/HTML for further use. I've got randomly generated number that I need to use later so I'm saving it as data-spin
on parent element.
When I'm trying to access the data, it stays the same - it's set once and even when the value is changed, the variable still says the first value.
$('#parent').scroll(function() {
var number = 1 + Math.floor(Math.random() * (12));
$('#parent').attr('data-spin', number);
console.log($('#parent').data('spin'));
});
I tried attaching the function to .scroll
function or no function at all but the result is same.
I'm attaching the jsfiddle example. The random number is logged at the first line, stored data at second.
Any ideas why it's not taking the current value of the field?
The variable is used in different function so I can't use the number
variable.
https://jsfiddle.net/orou3kLy/
Upvotes: 2
Views: 1317
Reputation: 7575
tl;dr: .data
and .attr
are different approaches to store data. .attr
stores your data directly as an attribute. I guess for your approach, you should save your number with .data
as it keeps the data type as well.
Also, for better performance, store the jQuery selector in a variable, because querying each scroll cycle takes time.
And one last thing: number
often is used as a type description in JavaScript (or better in some JS extensions like TypeScript and Flow). So it would be better to rename your variable there.
Here a working example:
const $parent = $( '#parent' );
$parent.scroll(function() {
var num = 1 + Math.floor(Math.random() * (12));
$parent.data('spin', num);
console.log($parent.data('spin'));
});
#parent {
background: lightgreen;
max-width: 300px;
max-height: 300px;
overflow: auto;
}
.content {
min-height: 200vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="content">---</div>
</div>
Upvotes: 3
Reputation: 1690
You could read attribute value the same way you write it:
$('#parent').attr('data-spin');
You have to be carefull though, because all values in attributes are strings. As to data
peculiar behaviour I suggest having a close look a the JQuery documentation, using data is not very intuitive.
Upvotes: 2
Reputation: 16384
It's because you are reading data incorrectly. You're using:
$('.kid').html('<strong>number:</strong> ' + number + '<br><strong>data:</strong> ' + $('#parent').data('spin'));
But instead of $('#parent').data('spin')
you need to use $('#parent').attr('data-spin')
. Here is the working fiddle: https://jsfiddle.net/orou3kLy/2/
Upvotes: 2
Reputation: 8209
They are not stored the same way.
Try storing using the same way you get the data:
$('#parent').scroll(function() {
var number = 1 + Math.floor(Math.random() * (12));
$('#parent').data('spin', number);
console.log($('#parent').data('spin'));
});
Upvotes: 3