Implementing CSS counter-increment with jQuery

Is there a way to use jQuery to set the CSS counter-increment attribute on ".demo:before" even though jQuery cannot access pseudo elements directly? I recall seeing a suggestion on Stack Overflow about using a data attribute and then referencing that value in the CSS, but it doesn't seem to be working for me. Can this actually be achieved?

Here's a simplified example to illustrate my question: http://jsfiddle.net/4h7hk8td/

HTML:

<ul class="demo">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

JS:

// 1) The user defines the unit size
var myUnit = 100;

// 2) Saving the unit size as a data attribute
$('.demo li').attr('data-unit', myUnit);

CSS:

.demo {
    counter-reset: list;
}

.demo li:before {
    /* 3) Attempting to get the data attribute with jQuery and use it as an increment - currently not functioning as intended :( */
    counter-increment: list attr(data-unit);
    content: counter(list);
}

Answer №1

If you're looking to simplify your CSS workflow, consider using a css-preprocessor for compiling the code.

For example, let's take a look at how this can be done using SCSS:

This method allows for different counter increments based on specific numbers provided. It works well when you have predetermined values for incrementing. For instance, if the values in question are 100, 200, and 300, you can use an @each loop to generate CSS for these known numbers.

If you have a general idea of the range of values being passed, you can also utilize an @for loop (especially useful with 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);
}

Check out this Working Fiddle (modify the data-num attribute value to 200 or 300)

Below is the compiled CSS output:

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

Answer №2

For each li, the counter should be increased, not for :before. Here is a demo of how to do this: http://jsfiddle.net/7vt0kf2c/.

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

Answer №3

Here is an alternative approach that achieves the desired outcome without using CSS:

let unitSize = 50;
$('.example').data('size', unitSize);
$('.example li').each(function () {
    $(this).text($('.example').data('size') * ($(this).index() + 1));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Having trouble with localstorage.setitem function in Angular?

Check out the function below. I can see an object in the console.log using res: login2(){ console.log(this.user_form_value); console.log(this.password_form_value); this._loginService.login(this.user_form_value, this.password_form_value).subscr ...

retrieving identifiers from a separate table for an array of values

As a newcomer to node and noSQL databases, I am facing challenges in grasping the concept of passing an array of IDs and retrieving the corresponding values from another table. I have 'users' and 'products' tables in my database. The st ...

Using jQuery to append a string to a CSS property

My current task involves modifying a series of divs with background images named Look-1.jpg to Look-6.jpg. I am looking to add "-cut" to all of them simultaneously to transform them into Look-6-cut.jpg. I have two collections of background images and I ai ...

Halting execution: Trying to use the keyword 'import' which is not allowed here

0. April 2023: error cannot be reproduced anymore see here The error is no longer replicable due to bug fixes in react-scripts 5.0.1. 1 Even though the error is gone, the question and my self-answer still seem relevant to Angular users and others as we ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: The main query is whether it is acceptable in HTML to write <span></span> followed by a <textarea>< ...

Troubleshooting Checkbox Problems on Internet Explorer 6

In order to have checkboxes generated dynamically for a pop-up window utilizing AJAX, I am using Javascript. Furthermore, when a button is clicked, a function needs to be executed that checks all the checkboxes before the pop-up appears. The web pages bei ...

Child functional component does not refresh after its props are altered by its parent component

Looking at the following code: MainParentComponent.js let data = 0; function MainParentComponent() { function handleClick() { data++; } return (<> <button onClick={handleClick}>Increase</button> < ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

The user removal process is not functioning properly

I'm encountering an issue in my Angularfire project while trying to remove a user. The email and password are being passed correctly, but the method responsible for user removal isn't getting executed. Below is the snippet of code from my Authent ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

Vue Checkboxes - Maintain selection unless a different checkbox is selected

I have implemented a checkbox system with radio button behavior, but I am facing an issue where I want to keep the checkbox checked until another checkbox is selected (which will then uncheck the first one). I do not want the ability to deselect the checkb ...

The sticky menu feature in jQuery does not assign classes to elements after the page is refreshed; it will only work when scrolling is activated manually

Currently, I am customizing a WordPress theme and have incorporated this jQuery code snippet to ensure that the menu sticks to the top of the page when the user scrolls down: /* ----------------------------------------- Fixed navigation on scroll -------- ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Clicking on a new tab causes the page to quickly scroll back to the top (jQuery Tabs

Currently, my website is utilizing jQuery tabs with AJAX functionality. Here is the HTML code: <div id="tabs"> <ul> <li><a id='tab-1' href="/get-1.htm">1</a></li> <li><a id=' ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the following line of code: chrome_o ...

Triggering a re-render in React

There are times when I find myself needing to trigger a re-render while still in the middle of executing a function. As a solution, I've developed a method using the state variable my_force_update. Basically, I change it to a random value when I want ...

Linking promises together ensures that they always resolve with a result

My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows: I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if i ...

Guide to recursively iterating through an array of objects in TypeScript/Javascript

In my current programming challenge, I am dealing with an array of objects that have two properties: target and source. Additionally, there is a designated starting source to begin with. The goal is to start from the starting source and recursively find a ...

The styles for the React calendar are not being properly applied to the calendar component due to CSS overriding

Having trouble overriding the default Calendar.css file in NextJS while creating a calendar component. Even after adding my own custom styles, they aren't being applied. Deleting the css file contents doesn't change the format either. Only when c ...