Quinox Quinox - 7 months ago 9
Javascript Question

How to trigger animate() on click with jQuery

I have skillbars with a background animation. It's just fine when the skillbars are initially visible but when I've to trigger the button for making the skillbars visible, the animation doesn't seem to work. Actually it works but just I push an another button.

Thanks in advance and sorry for my english !

Here's my fiddle
https://jsfiddle.net/mnvfdkf4/2/

Bootstrap doc: http://getbootstrap.com/javascript/#collapse

HTML

<a class="btn btn-secondary collapse-control" type="button" data-toggle="collapse" href="#collapseLangages" aria-expanded="true" aria-controls="collapseLangages">Langages</a>
<a class="btn btn-secondary collapse-control" type="button" data-toggle="collapse" href="#collapseFrameworks" aria-expanded="false" aria-controls="collapseFrameworks">Frameworks</a>
<a class="btn btn-secondary collapse-control" type="button" data-toggle="collapse" href="#collapseCMS" aria-expanded="false" aria-controls="collapseCMS">CMS</a>

<div class="collapse in" id="collapseLangages">
<div class="skillbar clearfix " data-percent="90%">
<div class="skillbar-title" style="background: #E34F26<span>HTML5</span></div>
<div class="skillbar-container">
<div class="skillbar-bar" style="background: #e67e22;"></div>
</div>
<div class="skill-bar-percent">90%</div>
</div> <!-- End Skill Bar -->
<div class="skillbar clearfix " data-percent="90%">
<div class="skillbar-title" style="background: #2980b9;"<span>CSS3</span></div>
<div class="skillbar-container">
<div class="skillbar-bar" style="background: #3498db;"></div>
</div>




jQuery

function animateSkillbar(){
$('.in .skillbar').each(function(){
$(this).find('.skillbar-bar').animate({
width:$(this).attr('data-percent')
},5000);
});
}
animateSkillbar();

$( ".collapse-control" ).on( "click", function() {
animateSkillbar();
});

Answer

The problem is that after clicking class in is not already set. So you need catch shown.bs.collapse event when collapse element has been made visible to the user:

$('.collapse').on('shown.bs.collapse', function () {
  animateSkillbar();
})

[ https://jsfiddle.net/0qa3u3wu/ ]