Jump to content

soabou

Members
  • Posts

    1
  • Joined

  • Last visited

soabou's Achievements

Newbie

Newbie (1/7)

0

Reputation

  1. This JavaScript code below updates numbers from 0 to maximum target numbers that we can choose from a no code builder. We can also set different styles to these numbers, like the color. For example, I set the first number to 150 and its color to yellow. When the numbers are being updated, they are able to stop to the maximu numbers we chosed in the no code application. So, the first number reaches 150 and stops. However, the problem is when the updateCount() function starts and resets the numbers to 0, it clears all the styles set through the builder before. So, the numbers will start from 0 and will get a black color. I would like the numbers to be updated and keep their native styles. So, the first number will start from 0 with the color of yellow and stops when reaches 150. During all this update the styles should remain. How can I manage this? I was thinking of fetching the styles and add them to values, but I didn't find any solution? I used IA tools like Google Bard, but I didn't find any solution for 2 days now. Here is the code: <script> class Counter { constructor(id, target, speed, appendString) { this.id = id; this.target = target; this.speed = speed || 1000; this.counter = document.querySelector(`#${id}`); this.count = 0; this.appendString = appendString || ''; } updateCount() { if (this.count < this.target) { this.counter.innerText = `${this.count} ${this.appendString}`; this.count++; setTimeout(() => this.updateCount(), this.speed); } else { this.counter.innerText = `${this.target} ${this.appendString}`; } } } const ids = [ 'headline-e6423da8', 'headline-77ad9299', 'headline-8255ec52', 'headline-5e08a0cb' ]; const values = []; for (const id of ids) { const value = document.querySelector(`#${id}`).innerText; values.push(value); } const counters = [ new Counter('headline-e6423da8', values[0], 10, ''), new Counter('headline-77ad9299', values[1], 15, ''), new Counter('headline-8255ec52', values[2], 20, '%'), new Counter('headline-5e08a0cb', values[3], 25, '+') ]; window.addEventListener('scroll', () => { counters.forEach(counter => { if ( pageYOffset > counter.counter.offsetTop - counter.counter.offsetHeight - 500 && counter.activated === false ) { counter.counter.innerText = 0; counter.count = 0; counter.activated = true; counter.updateCount(); } else if ( pageYOffset < counter.counter.offsetTop - counter.counter.offsetHeight - 500 || (pageYOffset === 0 && counter.activated === true) ) { counter.counter.innerText = 0; counter.activated = false; } }); }); </script> Every number has an id. So, the 4 ids 'headline-e6423da8', 'headline-77ad9299', 'headline-8255ec52' and 'headline-5e08a0cb' belong to the 4 numbers. I was able to fectch and display the values of these ids. However, I can't display them with their styles.
×
×
  • Create New...