In my current project, I am working on creating HTML and CSS-based bar representations of percentage values. The structure of the code is as follows:
Using HTML:
<div class="chart">
<div class="bar" style="width:43%"></div>
</div>
With CSS styling:
.chart {
background-color: #DADADA;
height: 2px;
position: relative;
}
.chart .bar {
background-color: #3D98C6;
height: 100%;
}
The goal I have in mind is to initiate the bar width at 0% upon page load, then smoothly animate it to the specified inline value. I prefer having the value inline so that our backend developers can easily integrate Ruby on Rails to output the desired percentage within the view. My initial approach includes implementing transitions as shown below:
CSS Implementation:
.chart .bar {
-moz-transition: width 1.25s linear;
-webkit-transition: width 1.25s linear;
-ms-transition: width 1.25s linear;
-o-transition: width 1.25s linear;
transition: width 1.25s linear;
}
body.jquery.csstransitions:not(.loaded) .chart-container .chart .bar {
width: 0% !important;
}
Utilizing JavaScript:
$(function() {
$('body').addClass('jquery');
// Further down in the script
$('body').addClass('loaded');
});
This method relies on jQuery to add classes "jquery" and "csstransitions" only if JavaScript is enabled and CSS transitions are supported by the browser. However, there is a potential risk of bars displaying with 0% width if the script breaks before adding the "loaded" class. To address this issue, I am considering utilizing CSS keyframe animations to achieve the same effect without depending on JavaScript.
By incorporating CSS-based animations from 0% width to the designated value, I aim to eliminate the variable of JavaScript errors impacting the functionality of the charts. This approach ensures a more reliable performance by either animating the bars seamlessly or loading them statically sans animation effects.
Is there a technique available to animate/transition width during page load while minimizing reliance on JavaScript?