DEV Community

Zarrukh Jurakulov
Zarrukh Jurakulov

Posted on

JavaScript Simple Counter

Hi everyone! We make counter today.
Firstly create 3 files index.html, script.js, style.css.
Firstly open html file and and connect with css and js file.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Counter</title>
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
    <div class="header">
        <h1>Js mini projects: <span class="mainHeader">Counter</span></h1>
    </div>
    <div class="main">
      <button onclick="decrease()" type="button" name="button" id="minusBtn">-</button>
        <h1 id="countNumber">0</h1>
      <button onclick="increase()" type="button" name="button" id="plusBtn">+</button>
    </div>
    <script src="./script.js" charset="utf-8"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Secondle, we should give some styling.

.header {
  background-color: lightgray;
  width: 30%;
  text-align: center;
  height: auto;
  padding: 3px;
}

.mainHeader {
  color: darkblue;
}

.main {
  background-color: lightgray;
  width: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 500px;
  margin: auto;
  margin-top: 50px;
}

button {
  margin: 10px;
  padding: 10px;
  background: darkgray;
  font-weight: bold;
  width: 50px;
}

Enter fullscreen mode Exit fullscreen mode

Thirdly, we go to the js file.
First of all, we declare a variable equal to 0.

let countingNumber = 0
Enter fullscreen mode Exit fullscreen mode

Then, create two function named increase and decrease.

const decrease = () => {}
const increase = () => {}
Enter fullscreen mode Exit fullscreen mode

Then in function we get value of countNumber with id

const decrease = () => {
  document.getElementById("countNumber").innerHTML;
};
const increase = () => {
  document.getElementById("countNumber").innerHTML;
};
Enter fullscreen mode Exit fullscreen mode

for counting we write prefix increment and prefix decrement operator.

const decrease = () => {
  document.getElementById("countNumber").innerHTML = --countingNumber;
};
const increase = () => {
  document.getElementById("countNumber").innerHTML = ++countingNumber;
};
Enter fullscreen mode Exit fullscreen mode

Full of width of js file.

let countNumber = 0;

const decrease = () => {
  document.getElementById("countNumber").innerHTML = --countNumber;
};

const increase = () => {
  document.getElementById("countNumber").innerHTML = ++countNumber;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)