Search code examples
javascriptjquerycsscountercss-counter

Set CSS counter-increment via jQuery


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);
}

Solution

  • Increment the counter for each li and not :before: http://jsfiddle.net/7vt0kf2c/.

    var myUnit = 100;
    $(".demo li").css("counter-increment", "list " + myUnit);
    $("button").click(function(e) {
        $(".demo li").css("counter-increment", "list " + 200);    
    });