JS 3 - JS CSS HTML Animated Counter

By Sheldon L Published at 2020-03-04 Updated at 2020-03-04


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Animated Counter</title>

  <link rel="stylesheet" href="style.css">
  <script src="https://kit.fontawesome.com/330a161b4f.js" crossorigin="anonymous"></script>
</head>
<body>
  <header>
    <div class="container">
      <h1>Animated Counter</h1>
    </div>
  </header>

  <section class="counters">
    <div class="container">

      <div>
        <i class="fab fa-youtube fa-3x"></i>
        <div class="counter" data-target="1000">0</div>
        <h3 style="font-size: medium;">Subscribers</h3>
      </div>
      <div>
        <i class="fab fa-twitter fa-3x"></i>
        <div class="counter" data-target="2000">0</div>
        <h3 style="font-size: medium;">Followers</h3>
      </div>
      <div>
        <i class="fab fa-facebook fa-3x"></i>
        <div class="counter" data-target="3000">0</div>
        <h3 style="font-size: medium;">Likes</h3>
      </div>
      <div>
        <i class="fab fa-linkedin fa-3x"></i>
        <div class="counter" data-target="4000">0</div>
        <h3 style="font-size: medium;">Connections</h3>
      </div>

    </div>
  </section>

  <script src="script.js"></script>
</body>
</html>
@import url('https://fonts.googleapis.com/css?family=Roboto&amp;display=swap');

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Roboto', sans-serif;
  background: lightskyblue url();
  color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  overflow: hidden;
}

header {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

header h1 {
  font-size: 48px;
  text-align: center;
}

.counters {
  background: #0f479a;
  padding: 2% 5%;
  border-top: 3px #ffffff solid;
  color: #ffffff;
}

.counters .container {
  display: grid;
  grid-gap: 30px;
  grid-template-columns: repeat(4, 1fr);
  text-align: center;
}

.counters i {
  color: lightskyblue;
  margin-bottom: 5px;
}

.counters .counter {
  font-size: 24px;
  margin: 15px;
}

@media (max-width: 700px) {
  .counters .container {
    grid-template-columns: repeat(2, 1fr);
  }
  .counters .container > div:nth-of-type(1),
  .counters .container > div:nth-of-type(2) {
    border-bottom: 1px lightskyblue solid;
    padding: 20px;
  }
}
const counters = document.querySelectorAll('.counter');
const speed = 200;

counters.forEach(counter => {
  const updateCount = () => {
    const target = +counter.getAttribute('data-target');
    const count = +counter.innerText;
    const inc = target / speed;

    if (count < target) {
      counter.innerText = count + inc;
      setTimeout(updateCount, 1)
    } else {
      count.innerText = target
    }
  }

  updateCount()
})