JavaScript to achieve balance digital scrolling effect

JavaScript to achieve balance digital scrolling effect

1. Implementation Background

Last week, in an activity where users completed tasks and received red envelopes, we needed to implement a pop-up window for receiving red envelopes after the user clicked a button. When the pop-up window was closed and the user returned to the original page, the balance number on the page had to display the effect of scrolling each digit.
Because I had never done such an effect before, I didn’t know how to achieve it at first. I wanted to find a related library on GitHub and saw a library with the highest star, but found that it depended on jQuery and could not be introduced through npm package. It feels unnecessary. The original project was based on the react framework, which aims to minimize DOM operations. In order to solve the scrolling problem, jQuery has to be introduced, which doesn't seem appropriate. So I decided to implement it myself, first looked at other people's ideas, and then implemented it myself.

2. Implementation ideas

In fact, it is to split the incoming n-digit number with rolling into each number to be rolled, and then dynamically create a container containing the corresponding numbers rolled to each digit, and then put it into the incoming target container. Scrolling to each corresponding number can be achieved by dynamically creating div with intervals from 0 to the corresponding number. The contents of the divs are the corresponding numbers, just like a long vertical paper with numbers from 0 to n, and then pulling it from 0 to the target number within a specified time.

3. Implementation process

Since we need to encapsulate it, let's write it in the form of class . Without further ado, let's go straight to the code.

/**
 * Class that implements the digital scrolling effect*/
class DigitScroll {
  constructor(options) {
    //Get the container's DOM. If not, an error is thrown this.container = document.querySelector(options.container);
    if (!this.container) {
      throw Error("no container");
    }
    this.container.style.overflow = "hidden";
    this.container.style.display = "flex";
    //The height of the visible container is also the scrolling interval. The height of the container must be set, otherwise the default is 30px
    this.rollHeight = parseInt(getComputedStyle(this.container).height) || 30;
    this.container.style.height = this.rollHeight + "px";
  }
  roll(num) {
    // Split the number passed in to be scrolled and initialize the container of each digit this.initDigitEle(num);
    const numEles = this.container.querySelectorAll(".single-num");
    // Traverse and generate the scroll queue for each digit. For example, if the scroll reaches 7, generate 7 divs with contents of 0, 1, 2, 3, 4, 5, 6, and 7 for scrolling animation [...numEles].forEach((numEle, index) => {
      const curNum = 0;
      let targetNum = Number(this.numberArr[index]);
      if (curNum >= targetNum) {
        targetNum = targetNum + 10;
      }
      let cirNum = curNum;
      // Document fragments, put together and insert into the node at once const fragment = document.createDocumentFragment();
      // Generate divs corresponding to the target number from 0 to
      while (targetNum >= cirNum) {
        const ele = document.createElement("div");
        ele.innerHTML = cirNum % 10;
        cirNum++;
        fragment.appendChild(ele);
      }
      numEle.innerHTML = "";
      numEle.appendChild(fragment);
      //Reset position numEle.style.cssText +=
        "-webkit-transition-duration:0s;-webkit-transform:translateY(0)";
      setTimeout(() => {
        numEle.style.cssText += `-webkit-transition-duration:1s;-webkit-transform:translateY(${
          -(targetNum - curNum) * this.rollHeight
        }px);`;
      }, 50);
    });
  }
  // Initialize the container initDigitEle(num) {
    //Number splitting digits const numArr = num.toString().split("");
    // Document fragments, put together and insert into the node at once const fragment = document.createDocumentFragment();
    numArr.forEach((item) => {
      const el = document.createElement("div");
      // Numbers are scrolled, non-numbers such as . are not scrolled if (/[0-9]/.test(item)) {
        el.className = "single-num";
        el.style.height = this.rollHeight + "px";
        el.style.lineHeight = this.rollHeight + "px";
      } else {
        el.innerHTML = item;
        el.className = "no-move";
        el.style.verticalAlign = "bottom";
      }
      // el.style.float='left';
      fragment.appendChild(el);
    }, []);
    this.container.innerHTML = "";
    this.container.appendChild(fragment);
    //Store the scrolling numbers this.numberArr = numArr.filter((item) => /[0-9]/.test(item));
  }
}

This is the end of this article about how to use JavaScript to achieve scrolling balance numbers. For more information about how to use JavaScript to achieve scrolling balance numbers, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • js realizes digital scrolling special effects
  • Vue.js realizes large-screen digital scrolling and flipping effects
  • CountUp.js realizes digital scrolling effect
  • Detailed explanation of how to use the CountUp.js digital scrolling plugin
  • CountUp.js realizes the effect of digital scrolling value-added

<<:  Use Meta to cancel the traffic cache to refresh the page every time you visit it for easy debugging

>>:  border-radius is a method for adding rounded borders to elements

Recommend

Sharing of experience on repairing MySQL innodb exceptions

A set of MySQL libraries for testing. The previou...

React new version life cycle hook function and usage detailed explanation

Compared with the old life cycle Three hooks are ...

Detailed explanation of the group by statement in MySQL database group query

1: Statement order of grouping function 1 SELECT ...

The benefits and examples of placing the site map at the bottom of the web page

In the past, almost every website had a sitemap p...

Detailed explanation of Zabbix installation and deployment practices

Preface Zabbix is ​​one of the most mainstream op...

How to write a Node.JS version of a game

Table of contents Overview Build Process Related ...

Detailed explanation of Nginx rewrite jump application scenarios

Application scenario 1: Domain name-based redirec...

How to find out uncommitted transaction information in MySQL

A while ago, I wrote a blog post titled "Can...

Vue imports Echarts to realize line scatter chart

This article shares the specific code of Vue impo...

Detailed analysis of MySQL master-slave delay phenomenon and principle

1. Phenomenon In the early morning, an index was ...

Example of compiling LNMP in Docker container

Table of contents 1. Project Description 2. Nginx...

IIS and APACHE implement HTTP redirection to HTTPS

IIS7 Download the HTTP Rewrite module from Micros...

Mysql implementation of full-text search and keyword scoring method example

1. Introduction Today a colleague asked me how to...

Solution to the problem of saving format in HTML TextArea

The format of textarea can be saved to the databas...