The demo for the tutorial is here
If there were no segments, it'd have been easier to implement the progress bar. But the progress bar itself is divided into segment like in the picture above. So before writing the range function, there are some initialization to be done to know in which bar the percentage falls on.
If the truePercent = 78, the rangeIndicator = 78/14.28 = 5.46 ~= 5. Thus the potentialLabel = 'medium'.
Let's break the function into multiple parts.
The loop basically runs from 1 to BAR_COUNT value.
This variable will give the percent which we'll compare with truePercent to know up to where the bar should be filled.
i.e Math.round(1 * 14.28) = 14
Math.round(2 * 14.28) = 28.56 ~= 29 and so on.
If not, then further calculation needs to be done.
The linear-gradient css property can be used to make different sorts of gradient effect. To achieve the effect of half filled and half empty, we need to know how much the filled percent is. The basic syntax for linear-gradient is
background-image: linear-gradient(90deg, color percent, white percent);
The above percent will become
((78 - 72)/14) * 100 = 42.85 ~= 42
Thus the percent for gradient is 42% and for white is (100-42) = 58% and the quartileValue = 6.
When the loop reaches to the quartileValue, the root.style.setProperty will set the percent value to the ith block. The left value set above is use to position the indicator exactly at the gradient separation part. The element is then pushed into array and the class is set according to the condition satisfied.
In this was, we can make progress bar indicator with the user defined percent value. Feel free to comment if the code is confusing :).
I hope this tutorial will be useful for some of you in coming days. Will return soon with another tutorial.