I need to change the fill of the bar as a function of time. In case, I need to change the progress: after width. How can I do this?
You can not directly change the style of a pseudo-elemento
, such as :after
.
However, you can add specific rules directly in browser-interpreted styles.
For this we can use the .addRule
method of the CSSStyleSheet
.
However, it is worth noting that this method is not supported in all browsers.
To ensure that the code works, let's create an auxiliary function responsible for verifying that the browser supports the .addRule
method. If not, let's work with the direct rewriting of the CSS property we want to change.
The helper function created for the example was:
function changeRule(selector, property, value) {
var stylesheet = document.styleSheets[0];
if (stylesheet.addRule) {
stylesheet.addRule(selector, property + ': ' + value);
} else {
var rules = stylesheet.cssRules;
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule.selectorText == selector) {
rule.style[property] = value;
}
}
}
}
Here is an example of usage:
var INCREMENT_FACTOR = 25;
function changeRule(selector, property, value) {
var stylesheet = document.styleSheets[0];
if (stylesheet.addRule) {
stylesheet.addRule(selector, property + ': ' + value);
} else {
var rules = stylesheet.cssRules;
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule.selectorText == selector) {
rule.style[property] = value;
}
}
}
}
var progressInterval = setInterval(function() {
var progress = document.getElementById('progress');
var maximumWidth = parseInt(window.getComputedStyle(progress).getPropertyValue('width'));
var currentWidth = parseInt(window.getComputedStyle(progress, '::after').getPropertyValue('width'));
var newWidth = currentWidth + INCREMENT_FACTOR;
changeRule('#progress::after', 'width', newWidth + 'px');
if (newWidth == maximumWidth) {
clearInterval(progressInterval);
alert('success!');
}
}, 500);
#progress {
background: #000000;
border-radius: 13px;
height: 20px;
width: 400px;
padding: 3px;
}
#progress:after {
content: '';
display: block;
background: white;
width: 0;
height: 100%;
border-radius: 9px;
}
<div id="progress"></div>
Read more about this in Modify pseudo element styles with JavaScript .