Reputation: 41
#me {
background-color: blue;
color: white;
width:150px;
padding: 5px;
position: relative;
}
<div id='me'>Here we go</div>
OK, I'm trying to set CSS properties of the $.animate method to values stored in the DOM element using the $.data method. Now this works
$('#me').data().moveto = 50;
$('#me').animate({ left: '+=' + $('#me').data('moveto') }, 2000, function() {
$(this).text('Finished: '+$(this).data('moveto'));
});
But this doesn't
$('#me').data().moveto = 50;
$('#me').animate({ left: '+=' + $(this).data('moveto') }, 2000, function() {
$(this).text('Finished: '+$(this).data('moveto'));
});
Nothing happens. Now should this second method not work?
And in both cases the this is recognised and the text is set to Finished: 50.
Cheers.
Upvotes: 4
Views: 203
Reputation: 434665
In here:
$('div').animate({ left: '+=' + $(this).data('moveto') }, 2000);
the this
is going to be the same this
that it was outside the function call so that is equivalent to this:
var self = this;
$('div').animate({ left: '+=' + $(self).data('moveto') }, 2000);
and self
probably isn't the <div>
you're looking for so $(this).data('moveto')
returns undefined
and you end trying to do:
$('div').animate({ left: '+=' }, 2000);
which doesn't do anything useful. Try this example and you should see what's going on:
Also, you're probably better off doing:
$('#me').data('moveto', 50);
instead of:
$('#me').data().moveto = 50;
As you found in the docs (thank's for the heads up on that BTW), $x.data()
will return the data object but interesting things might happen if $x
matches more than one DOM element.
Upvotes: 1