I have a very simple html code that has only one button tag. I need to count the number of mouse clicks on the button using javascript. Here is a screenshot of the Javascript code in VScode
-
2Please edit your question and copy/paste your code. It's much simpler for us to work with code then with imagescaramba– caramba2021-06-12 15:46:22 +00:00Commented Jun 12, 2021 at 15:46
-
1Please post the code here so that it'd be easy to copy and execute.junkie– junkie2021-06-12 15:47:52 +00:00Commented Jun 12, 2021 at 15:47
-
Does this answer your question? Count clicks on element with JavaScriptLouys Patrice Bessette– Louys Patrice Bessette2021-06-12 15:52:35 +00:00Commented Jun 12, 2021 at 15:52
-
I have also found it, but it is not with event listenerMetropolisCZ– MetropolisCZ2021-06-12 15:53:53 +00:00Commented Jun 12, 2021 at 15:53
-
1Images of code are not acceptable.Spectric– Spectric2021-06-12 16:03:40 +00:00Commented Jun 12, 2021 at 16:03
Add a comment
|
2 Answers
Well, the code below can implement count on click functionality.
let clicks = 0;
document.querySelector('.btn').addEventListener('click', e => {
clicks++;
document.querySelector('.clicks').textContent = clicks
})
.btn {
border: none;
outline: none;
background-color: purple;
padding: 1rem 90px 1rem 2rem;
position: relative;
border-radius: 8px;
letter-spacing: 0.7px;
background-color: #5086bd;
color: #fff;
font-size: 21px;
font-family: "Lato", sans-serif;
cursor: pointer;
box-shadow: rgba(0, 9, 61, 0.2) 0px 4px 8px 0px;
}
<button class="btn"> Click me </button>
<div>
<p>You have clicked the button <span class="clicks"> 0</span> times</p>
</div>
Comments
Why not this?
let numberOfClicks = 0;
function addclick() {
numberOfClicks++;
document.getElementById('clicks').innerHTML = numberOfClicks;
}
document.getElementById("clickme").addEventListener("click", addclick);
<button id='clickme'>Click me!</button>
<p id='clicks'>0</p>
Update: Solution with event listener