Skip to content
Advertisement

Trying to build a counter, very basic javascript question

I’m pretty new to writing code and I am using JavaScript and HTML in Visual Studio Code. I’ve been trying to solve the following exercise which is to create a button that counts how many times it is being pushed.

The HTML part is done, but I’m stuck in the JavaScript part.

Any advice to solve such a thing?

let counter

document.querySelector("#btnPush").addEventListener("click", plus)

function plus() {

    counter = 0;
    
    document.querySelector("#pCounter").innerHTML = counter + 1
    
}

Advertisement

Answer

let counter = 0

document.querySelector("#btnPush").addEventListener("click", plus)

function plus() {

  counter++;

  document.querySelector("#pCounter").innerHTML = counter

}
<button id="btnPush">button</button>
<p id="pCounter">0</p>
Advertisement