Anna
Anna

Reputation: 11

increasing a number inside of a mouseClicked funtion

I have a code where I draw an object when the mouse is clicked using mouseClicked = function(){} and then I need to have a number to show how many objects have been drawn. the problem is that the number won't increase. what do I do?

Upvotes: 1

Views: 89

Answers (4)

gavgrif
gavgrif

Reputation: 15509

Rather than declaring and incrementing a global variable - you could set the count as a HTML 5 data attribute on the button and then on clicking the button, get the data attribute value, increment it and update the display and the new count on the button.

Note that data-attributes are always strings - hence the need for the parseInt() method, though if I was being a purist - I would have put the radix in as well, but that defaults to 10 - so no need in this case.

It is always better to avoid global variable when possible and data attributes offer a very conveniant way of storing local data.

Thanks to @Sven.hig for the skeletn code of the solution - which I then modified to my approach.

var res=document.getElementById("res")
var btn=document.getElementById("btn")

btn.addEventListener("click",()=>{
  const newCount = parseInt(btn.getAttribute('data-count'))+1;
  res.textContent = newCount;
  btn.setAttribute('data-count', newCount)
})
<div id="res"></div>

<button id="btn" data-count="0">Draw</button>

Upvotes: 2

sonEtLumiere
sonEtLumiere

Reputation: 4572

this is an easy way to counter the clicks on a html document.

let counter = 0;    

document.onclick = () => {
    counter++;
    console.log(counter);
}

Upvotes: 0

Sven.hig
Sven.hig

Reputation: 4519

Here is a simple example that will give you an idea about how to increment a counter

var res=document.getElementById("res")
var btn=document.getElementById("btn")
var count=1
btn.addEventListener("click",()=>{
    res.textContent=count
    count++
    
})
<div id="res"></div>

<button id="btn">Draw</button>

Upvotes: 1

Symphonic
Symphonic

Reputation: 365

If the count variable is defined inside the mouseClicked function as the title say, you are recreating it in every mouseClick. In this case, you should define it outter the function with value = 0 and, inside the function, sum 1 to that value. Anyway, like the comments say, it's necessary that you include the code to your question to give a better answer.

Upvotes: 0

Related Questions