user1051849
user1051849

Reputation: 2337

JQuery animating based on variable attribute

We have multiple divs with the same class name that we would like to animate based on their given attribute values:

<div class="chart-bar"  style="width:10%;" bar-width="100%"></div>
<div class="chart-bar"  style="width:10%;" bar-width="70%"></div>
<div class="chart-bar"  style="width:10%;" bar-width="30%"></div>

When we attempt:

$(".chart-bar").animate({width: "60%"});

then this works fine (all divs are extended to 60%). However, when we try:

$(".chart-bar").animate({width: $(this).attr('bar-width')});

then nothing happens. I'm thinking that perhaps $(this) doesn't work in this context, but I'm currently out of ideas.

Thanks.

Upvotes: 2

Views: 33

Answers (1)

Rahul Patel
Rahul Patel

Reputation: 5246

Way 1:

Using $(".chart-bar").each(function(){ loop through all the divs with class .chart-bar and get the attribute value.

Please check below snippet.

$(".chart-bar").each(function(){
  $(this).animate({width: $(this).attr('bar-width')});  
});
.chart-bar{
  border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chart-bar"  style="width:10%;" bar-width="100%">Div-1</div>
<div class="chart-bar"  style="width:10%;" bar-width="70%">Div-2</div>
<div class="chart-bar"  style="width:10%;" bar-width="30%">Div-3</div>

Way 2:

Use $( ".chart-bar" ).attr( "bar-width", function( i, val ) { to get attribute for all the div and animate.

Please check below snippet.

$( ".chart-bar" ).attr( "bar-width", function( i, val ) {
  $(this).animate({width: val});  
});
.chart-bar{
  border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chart-bar"  style="width:10%;" bar-width="100%">Div-1</div>
<div class="chart-bar"  style="width:10%;" bar-width="70%">Div-2</div>
<div class="chart-bar"  style="width:10%;" bar-width="30%">Div-3</div>

Upvotes: 5

Related Questions