May Hitchings
May Hitchings

Reputation: 9

Javascript Counter Not Working with JSON Data

The counter works fine when I just insert a number straight into the HTML, but the data being pulled remotely isn't working. The remote data is console.logging out correctly, and it shows up correctly in the DOM element when the counter code is commented out. The typeof the remote data is returning as "number," but parseInt() is returning "NaN." Adding a + in front of the var in parseInt() is returning "0." I also tried encodeURIComponent() and that returned the correct value as well with no extra characters.

$(document).ready(()=>{

    let count;

    const getData = () => {
    
        $.ajax({
            url:'https://raw.githubusercontent.com/RAdrianKing/AUbeatweek/master/auburn.json',
            dataType: 'json',
            type: 'GET',
        }).then((response) => {
            console.log(response);
            count = response.DonorTotal;
      
            console.log(count);
            $('.count').append(count)
        })
    }

    getData()

})

And then in another js file loaded right after...

// COUNTER
 let start // set on the first step to the timestamp provided
 const elements = Array.from(document.getElementsByClassName('count')) // get the elements
 console.log(elements);

 elements.forEach(el => {
      const final = parseInt(el.textContent, 10) // parse out the final number
      console.log(final);
     const duration = 2000 // duration in ms
     const step = ts => {
     if (!start) {
         start = ts
     }
     // get the time passed as a fraction of total duration
     let progress = (ts - start) / duration 

     el.textContent = Math.floor(progress * final) // set the text
     if (progress < 1) {
         // if we're not 100% complete, request another animation frame
         requestAnimationFrame(step) 
     }
     }

     // start the animation
     requestAnimationFrame(step)
  })

Upvotes: 1

Views: 67

Answers (1)

May Hitchings
May Hitchings

Reputation: 9

Barmar, you were right! It's fixed! Thank you so much! I moved the second code block into the .then function and it worked like a charm!

Upvotes: 0

Related Questions