What's the best way to add a suffix to a dynamic counter animation?

Having trouble adding a static suffix to the end of animated counters. I want to include a "+" sign in some of them without animation.

I attempted to create a suffix class, but it doesn't append directly to the end value - it keeps showing up below the numbers. As a complete beginner, I apologize if there's an obvious solution that I'm missing! I've looked through the forums, but none of the approaches seem to match mine.

let values = document.querySelectorAll(".num");
let interval = 4000;

values.forEach((value) => {
  let startValue = 0;
  let endValue = parseInt(value.getAttribute("data-val"));
  let duration = Math.floor(interval / endValue);
  let counter = setInterval(function() {
    startValue += 1;
    value.textContent = startValue;
    if (startValue == endValue) {
      clearInterval(counter);
    }
  }, duration);
});
* {
  padding: 0;
  margin: 0;
  font-family: "Poppins", sans-serif;
}

body {
  background-color: white;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  height: 100vh;
}
// rest of CSS code here
<div class="wrapper">
  <div class="container">
    // HTML content
    // More HTML content here...
  </div>
</div>

Answer №1

To easily add a + sign, utilize the :after pseudo-element.

I did have to exclude the grid display for the .num elements as it affected the alignment of the added +.

Take a look at the CSS snippet below:

let valueDisplays = document.querySelectorAll(".num");
let interval = 4000;

valueDisplays.forEach((valueDisplay) => {
  let startValue = 0;
  let endValue = parseInt(valueDisplay.getAttribute("data-val"));
  let duration = Math.floor(interval / endValue);
  let counter = setInterval(function() {
    startValue += 1;
    valueDisplay.textContent = startValue;
    if (startValue == endValue) {
      clearInterval(counter);
    }
  }, duration);
});
.num:after {
  content: '+';
}

span.num {
  text-align: center;
}

/* This is all you need! */

* {
  padding: 0;
  margin: 0;
  font-family: "Poppins", sans-serif;
}

body {
  background-color: white;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  height: 100vh;
}

.wrapper {
  position: absolute;
  width: 80vw;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  display: flex;
  justify-content: space-around;
  gap: 10px;
}

.container {
  width: 28vmin;
  height: 28vmin;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding: 1em 0;
  position: relative;
  font-size: 16px;
  border-radius: 0.5em;
  backdrop-filter: blur(10px);
}

i {
  color: #000000;
  font-size: 3.8em;
  text-align: center;
}

span.num {
  color: #000000;
  font-weight: 600;
  font-size: 3em;
}

span.text {
  color: #000000;
  font-size: 1em;
  text-align: center;
  pad: 0.7em 0;
  font-weight: 400;
  line-height: 0;
}

@media screen and (max-width: 1024px) {
  .wrapper {
    width: 85vw;
  }
  .container {
    height: 26vmin;
    width: 26vmin;
    font-size: 12px;
  }
}

@media screen and (max-width: 768px) {
  .wrapper {
    width: 90vw;
    flex-wrap: wrap;
    gap: 30px;
  }
  .container {
    width: calc(50% - 40px);
    height: 30vmin;
    margin-bottom: 25px;
    font-size: 14px;
  }
}

@media screen and (max-width: 480px) {
  .wrapper {
    gap: 15px;
  }
  .container {
    width: 100%;
    height: 25vmin;
    font-size: 8px;
    margin-bottom: 25px;
  }
}
<div class="wrapper">
  <div class="container">
    <i class="fa-regular fa-face-laugh"></i>
    <span class="num" data-val="8">0</span>
    <span class="text">Apples</span>
  </div>

  <div class="container">
    <i class="fa-solid fa-users"></i>
    <span class="num" data-val="40000">0</span>
    <span class="text">Oranges</span>
  </div>

  <div class="container">
    <i class="fa-regular fa-circle-down"></i>
    <span class="num" data-val="2.3">0</span>
    <span class="text">Lemons</span>
  </div>

  <div class="container">
    <i class="fa-solid fa-podcast"></i>
    <span class="num" data-val="900">0</span>
    <span class="text">Pears</span>
  </div>
</div>

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

State is not being updated by useState after the second API call in MUI and ReactJS

I encountered an issue while using the Material-UI Autocomplete component for a search box. The problem arises when fetching options from an API and passing them to the component. Initially, the dropdown displays the options correctly. However, upon closin ...

Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure: - pages - articles - [slug].js - index.js - components - nav.js Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].j ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Retrieving the value of a specific <link> in XML using Javascript

I am utilizing Ajax/jQuery to fetch content from an RSS feed, but I'm encountering difficulties in retrieving the content of an XML node named 'link'. Below is a simplified version of the XML: <?xml version="1.0" encoding="UTF-8"?> ...

Evaluating operational Angular component - Error: $(...).somename function is not defined

I've encountered an issue while attempting to test my component in Angular. The component itself functions correctly during regular use, but when I try to run the tests using "yarn run test", I receive the following error message: HeadlessChrome 0.0. ...

What is the frequency of page rendering in Angular 2 before displaying it?

I've been working with Angular 2 on a project lately. In my template, I have a simple div that triggers a function in my .ts file to display basic text like so: <div>{{ test() }}</div> test(): void { console.log("Test text") ...

What could be causing my divs to not properly handle overflow with the overflow-y scroll property?

I'm struggling with making my sidebar and content area responsive in terms of height. I want them to adjust to fill the screen appropriately, rather than having a fixed height. The issue arises when I have varying content heights, such as when a page ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Is it possible for me to replicate this full-screen flash animation using jQuery?

I need some guidance on how to create an animation similar to the one on http://flatuicolors.com without using flash. When you click a color on the website, it triggers a full screen animation with text. I'm not asking for code, just ideas on how to ...

Tips for avoiding the forward slash in a URL parameter

$.ajax({ url: "/api/v1/cases/annotations/" + case_id + "/" + encodeURIComponent(current_plink), When I use encodeURIComponent to escape slashes, it doesn't work as expected. The code converts the "slash" to "%2F", but Apache doesn't reco ...

How can I use htaccess to forward all links within a specific folder to index.php with a GET variable attached?

Is it possible to redirect all links inside a folder to index.php while passing the file name as a GET variable? I have never worked with htaccess before and don't know how to search for it. For instance: localhost/folder/file-123 should redirect to ...

Creating user-friendly options for multi-checkbox forms using Django enums

I am facing an issue with my code where it only displays the shorter variable values for 'Plan 1' and 'Plan 2', rather than their longer human-readable forms that I have defined in the model. I am creating checkboxes in an HTML templat ...

Control the movement of the mouse pointer using javascript

For my University presentation on click-jacking, I came across an intriguing example that I wanted to replicate but didn't know where to start. The whole concept seemed very complex to me. To get a better idea, please take a look at this video: https ...

What occurs when a function component is passed as a state variable?

Can a function component be passed as a state variable? Is it possible for the code below to work correctly? I attempted it but encountered an error stating props.children isn't a function. Do you know if this approach can be successful? const App = ...

Launch a new window with the window.open() method and execute a function on the newly opened window

I am having trouble generating a barcode in a new window using the barcode generator script. Despite trying to use window.focus(), I can't get the barcode to appear in the new window. Any assistance on how to generate the barcode in a separate window ...

Learn the process of sending both Header and Body data in a POST request using Axios with Vue.js

I'm currently attempting to call the post API of AWS Cognito's Token endpoint. The API functions perfectly when tested in my Postman client, but I am encountering issues when implementing it in my VueJS code. Here is a snippet of my code: test. ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

What is the best way to populate a textarea element in Jade with text without any whitespace?

My current solution is functioning perfectly: textarea. #{myObject.myVar} Despite the success, Jade throws a warning when compiling the file: Cannot read property 'myVar' of undefined This warning makes sense since myObject may not be p ...