Reputation: 13
I am new to programming and I am working with a table on otree were 256 different buttons are displayed using Javascript. Each button unveils an icon which is recalled by a simple function.
In this function, I have installed a simple click counter that increases by one each time a button is clicked. The simple click counter works fine (that is not my issue) :)
The table:
for(var r = 0; r < rows;r++)
{
table += '<tr>';
for(var c= 0; c< cols;c++)
{
var random = Math.floor(Math.random() * nums.length);
table += '<td style="width:50px">' + '<button id="' + nums[random] + '" type="button" onclick="displayImage(this.id)">' + "show me" + '</button>' + '</td>';
nums.splice(random, 1);
}
table += '</tr>';
}
The function:
function displayImage(num){
document.canvas2.src = '{% static "bottone/'+ imagesArray[num]+ '.png" %}';
document.getElementById("YourImage2").style.visibility = "visible";
onClick();
}
The counter:
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
All good till here, there is a hidden HTML field and I manage to save the value of the counter when the user clicks the "next" button...
My problem is the following: this counter counts the amount of buttons clicked, however, I would like it to count only the number of times a button is clicked for the first time (could range from 0 to 256) while still enabling people to click the same button more times. I´m sure it can be really simple but have no idea where to start...
Upvotes: 1
Views: 665
Reputation: 1516
Here is a simple JSFiddle example:
HTML:
<button onclick="buttonClicked(event)">
New 1
</button>
<button onclick="buttonClicked(event)">
New 2
</button>
<button onclick="buttonClicked(event)">
New 3
</button>
<div id="counter">0
</div>
JS:
var clickedList = [];
var counter = 0;
function buttonClicked(event){
if (clickedList.indexOf(event.currentTarget) === -1){
clickedList.push(event.currentTarget);
counter++;
document.getElementById("counter").innerHTML = counter;
console.log(counter);
}
}
Upvotes: 0
Reputation: 1389
You can track for each button whether it was clicked before, and if so not count the click.
Your onClick function would look like this (note you should pass it the id of the clicked button):
var clicks = 0;
function onClick(id) {
var clickedEl = document.getElementById(id);
if (clickedEl.dataset.wasClicked) {
return;
}
clickedEl.dataset.wasClicked = true;
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
Upvotes: 1