Reputation: 25
I'm having trouble getting smooth animation on a div width that I've set as a variable. It's supposed to animate similar to a progress bar. I have a demo on JSfiddle. How can I get a smooth animation? Thank you!
HTML:
<div id="pb"><div></div></div>
<a href="#" class="test" data-value="25%">25</a>
<a href="#" class="test" data-value="50%">50</a>
<a href="#" class="test" data-value="75%">75</a>
<a href="#" class="test" data-value="100%">100</a>
jQuery:
$(function () {
$( "#pb div" ).width("50%");
$('.test').click( function () {
var value = parseInt($(this).attr('data-value'));
var test = $( "#pb div" ).css({width: (value) + '%'});
$('#pb div').animate({
width: test,
}, 1000);
});
});
Upvotes: 2
Views: 3379
Reputation: 600
Your line var test = ... is already changing the css width. Instead just use the animate function as below:
$(function () {
$( "#pb div" ).width("50%");
$('.test').click( function () {
var value = parseInt($(this).attr('data-value'));
test = $( "#pb div" ).animate({width: (value) + '%'});
});
});
Upvotes: 1
Reputation: 82337
jsFiddle Demo
You were already there :)
Just use your value in the animation instead of directly setting the width via the css property like this:
$('#pb div').animate({
width: value+"%",
}, 1000);
Upvotes: 2
Reputation: 298562
You're setting the same width with .css
and with .animate
, so it won't have any frames to animate:
$(function () {
$("#pb div").width("50%");
$('.test').click(function() {
$('#pb div').stop().animate({
width: $(this).data('value')
}, 1000);
});
});
Demo: http://jsfiddle.net/srQVv/1/
Upvotes: 0