Progetti JavaScript

In this article we will develop some simple JavaScript projects, such as displaying a counter that is incremented in various ways.

JavaScript projects – counter

In this first project we will build a counter using only Vanilla JavaScript.

Try clicking on the buttons below to increase or decrease the counter variable which starts from the initial value 0.

JavaScript Counter

0

How can we develop the code?

First here is the simple html code needed for our project.





We have inserted the button minus which has the function of decreasing the variable number and the button plus which instead has the function of increasing it.

To identify each element we used an id, in order to then be able to use the getElementById method in JavaScript.

We then add some simple CSS code of your choice. For example, I entered this:



.container {
    background-color: #2c45a3;
    text-align: center;
    padding: 20px;
    color: white;
}

h3 {
  font-size: 30px;  
}

button {
  font-size: 30px;
  background-color: #fc7180;
  color: #2c45a3;
  border: none;
  border-radius: 10px;
  padding: 10px 20px;
  cursor: pointer;
}

#number {
  font-size: 40px;
  padding: 0 50px;
}

And here is the JavaScript code that uses the addEventListener method to intercept the mouse click on the two plus and minus buttons.

What we will do by clicking the mouse on each button is simply to increase or decrease the value of the variable and write it in the element that has id number through the innerHTML property.



const number = document.getElementById('number');
const buttonPlus = document.getElementById('plus');
const buttonMinus = document.getElementById('minus');

buttonPlus.addEventListener('click', add);
buttonMinus.addEventListener('click', subtract);

let value = 0;

function add() {
  value++;
  number.innerHTML = value;
}

function subtract() {
  value--;
  number.innerHTML = value;
}

JavaScript projects – counter with different increment values

In this second example we increment the counter with different values: 1, 5, 10 or 100.

Then click on the various buttons to see the increase of the starting variable.

JavaScript Counter

0

In this second example we used the onclick event directly on the button in the HTML code.





You can see that we passed a second parameter depending on the value we want to increase.

Here is the JavaScript code:



const number = document.getElementById('number');

let value = 0;

function add(n) {
  value = value + n;
  number.innerHTML = value;
}

Conclusion

In this article we have developed a simple counter. We will then continue in the next articles to develop many interesting JavaScript projects.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *