JavaScript Counter

JavaScript Counter
Project: Simple Counter JS
Author: Jennifer Takagi
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create a counter. It defines a function called “increaseNumber” which increases a counter every second and updates an HTML element’s content with the new value. The counter starts at 0 and increments by 1 until it reaches 99, at which point it resets to 0. The HTML element to be updated is identified using its ID, “js-number”. The function is executed when the “load” event is triggered on the window object, which means it will start running when the page finishes loading.

The setInterval method is used to repeatedly call the startCount function every 1000 milliseconds (i.e., every second) to update the counter and the HTML element’s content.

How to Create JavaScript Counter

First of all, load the following assets into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Create the HTML structure for the counter as follows:

<div class="box-center text-center">
 	<header class="box-text">
 		<p class="info-text margin-0">Let's count them up!</p>
 	</header>
 	<main class="box-number">
 		<p class="number-text margin-0" id="js-number"></p>
 	</main>
 </div>

Now, style the counter using the following CSS styles:

/* Helpers */

.text-center {
	text-align: center;
}

.margin-0 {
	margin: 0;
}

/* Others */

body {
	position: relative;
	height: 100vh;
	margin: 0;
}

.box-center {
	width: 200px;
	text-align: center;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translateX(-50%) translateY(-50%);
}

.box-text {
	background-color: #000;
	line-height: 50px;
}

.box-number {
	background-color: #008100;
	line-height: 150px;
}

.info-text {
	color: #fff;
	font-size: 12px;
}

.number-text {
	color: #fff;
	font-size: 90px;
}

Finally, add the following JavaScript function for its functionality:

/**
	Increase number
**/
const increaseNumber = () => {
  let counter = 0;
  const numberElement = document.getElementById("js-number") || {};

  setInterval(function startCount() {
    counter < 99 ? numberElement.innerHTML = ++counter : counter = 0;
  }, 1000);
};

window.addEventListener("load", increaseNumber);

That’s all! hopefully, you have successfully created JavaScript counter. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *