Reputation: 13
I created a graph using html, now I want to give it a nice effect when it initially loads. I want the bars of the graph to fly in from the left. The code below does that, only problem is each bar ends up with 70% width (obviously since I set that in the jQuery code). Instead I need that number to be unique to the width set within the bars (span tags). I assume the answer would be something like:
$(this).attr('width')...
but I can't get it to work, please help.
The Code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<style type="text/css">
div.graph { display: none; border: 1px solid red; height: 200px; width: 400px; margin: 0 auto; }
div.graph span { display: none; display: block; background: red; height: 20px; margin-bottom: 10px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$('div.graph').fadeIn('slow');
$('div.graph > span').animate({
width: "70%"
}, 1500 );
});
</script>
<div class="graph">
<span style='width:10%'></span>
<span style='width:40%'></span>
<span style='width:25%'></span>
<span style='width:15%'></span>
<span style='width:10%'></span>
</div><!-- graph -->
Upvotes: 1
Views: 3991
Reputation: 11859
edit
After reading your code, if you don't care for non-JS support [there are many casex when you don't], you can use .data()
method [very elegant, too :)]
HTML:
<span data-width="10%">Hello</span>
JS:
$('div.graph > span').each(function(){
$(this).animate({
width: $(this).data('width')
}, 1500 );
});
updated example
code
.animate({
'width': $(element).width()
},500);
example
[updated with %]
Upvotes: 3
Reputation: 1715
$(this).width()
should work, or else $(this).css('width');
however .css('width')
will return the value that the css has, so could be '10%' for example or 'auto'
Upvotes: -1
Reputation: 10350
Try this on for size:
$('div.graph > span').each(function(){
var w=$(this).width();
$(this).width(0);
$(this).animate({
width: w
}, 1500 );
});
Upvotes: 1
Reputation: 979
Try this...
$('div.graph').fadeIn('slow');
var bars = $('div.graph > span');
for(var i=0; i<bars.length; i++){
var w = $(bars[i]).width();
$(bars[i]).width(0);
$(bars[i]).animate({
width: w
}, 1500);
}
Upvotes: 0
Reputation: 21522
you could do something like:
$(document).ready(function() {
$('div.graph > span').each(function() {
var $this = $(this);
var w = $this.width(); // Grab what it should be
$this.width(0); // Reset so it does the animation
$this.animate({
width: w
}, 1500 );
});
$('div.graph').fadeIn('slow');
});
It reads what you want the bar to be, then sets it back to 0. setting up the animation to go. After its all set, the fade in starts
Upvotes: 0