I need to change the fill of the bar as a function of time. In case, I need to change the width of the Progress:after. How can I do this?
Cannot directly change the style of a pseudo-elemento
, as is the case with :after
.
However, you can add specific rules directly into the styles interpreted by the browser.
For this we can use the method .addRule
of the object CSSStyleSheet
.
However, it is worth noting that this method is not supported on all browsers.
To ensure the code works, we will create an auxiliary function responsible for checking if the browser supports the method .addRule
. If not, we will work with the direct rewriting of the property CSS that we want to change.
The auxiliary 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 the use:
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 on the subject at Modify pseudo element Styles with Javascript.
@Sergio believe it is now ok. In the last change did not work because the method
.insertRule
in FF ends up replacing all the style instead of adding.– Romulo
Good! I already gave
+1
I think it’s great now. If you want to explain this Feature Detectstylesheet.addRule
would be excellent :P– Sergio