#4 Build a Simple Counter with Vanilla JS

#4 Build a Simple Counter with Vanilla JS

ยท

2 min read

To make my Vanilla JS strong I made this app that uses DOM elements.

It's very easy to build.

Let's Begin!!!

What are we going to make?

  • A counter which is going to have 3 buttons.
  • Input: the user clicks on a button.
  • Processing: according to the button clicked we increment, decrement, or reset the value.
  • Output: we show the user by updating the value in real-time.

Final Output

Hnet-image.gif

Step 1 : HTML

code.png

  • A div for showing the output which is initially 0.
  • 3 buttons with their respective ids.
  • Increase button to increment.
  • Reset button to make it 0.
  • Decrease button to decrement.

Step 2 : JavaScript

code.png

  • First, we select the buttons with their respective ids using document.querySelector and assign them to variables.
  • document.querySelector returns the respective CSS selector that matches it.

d.png

  • Again we use document.querySelector to select the output which displays our counter and assign it to a variable.

counter.png

  • Initially, our counter has to be 0.
  • We set the initial value to 0.

logic.png

Logic/Processing

  • We use addEventListener to the variables assigned to the buttons.
  • A click event is used so whenever the button is clicked a function is called.
  • So, now whenever we click the button the intitalValue increases by 1 .

Output

  • To display the count we set outputMsg.innerText to be initialValue which keeps getting changed whenever we click a button.

Step 3 : Adding CSS

  • Give it your own styling ๐Ÿ˜‰.

If you learned something new today why not connect with me?

Twitter

Github

Linkedin

ย