I want to set the CSS counter-increment attribute on ".demo:before
" using jQuery.
The problem is jQuery cannot access a pseudo element. Another S.O. answer (which I can't seem to find now) suggested setting a data-attribute, and then using that value within the CSS, but that isn't working either. Is this something that can be accomplished?
Simplified Example: http://jsfiddle.net/4h7hk8td/
HTML:
<ul class="demo">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
JS:
// 1) User Sets Unit Size
var myUnit = 100;
// 2) Unit size is saved via data attribute
$('.demo li').attr('data-unit', myUnit);
CSS:
.demo {
counter-reset: list;
}
.demo li:before {
/* 3) CSS gets data attribute and applies as the increment. Not working :( */
counter-increment: list attr(data-unit);
content: counter(list);
}
You can actually use a css-preprocessor to compile the css.
I am giving an example below using scss:
It actually renders different counter increments for the passed numbers. This solution will work if you already know the values which are being used to increment. For example, if the values being passed are 100
, 200
and 300
, then you can use @each
loop to compile css for those known numbers.
If you are atleast aware of range of values being passed, you can use @for loop
(use it when there are limited numbers).
$values: 100, 200, 300;
@each $i in $values {
.demo[data-num="#{$i}"]{
& > li::before{
counter-increment: list #{$i};
}
}
}
.demo {
counter-reset: list;
}
.demo li:before {
content: counter(list);
}
Working Fiddle (change the data-num
attribute value to 200 or 300)
Here is the compiled css:
.demo[data-num="100"] > li::before {
counter-increment: list 100;
}
.demo[data-num="200"] > li::before {
counter-increment: list 200;
}
.demo[data-num="300"] > li::before {
counter-increment: list 300;
}
.demo {
counter-reset: list;
}
.demo li:before {
content: counter(list);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With