I’m using a counter for button clicks and it’s working fine, but I would like to ask how I can make it cleaner and less repetitive and still do the same function?
To give a perspective, I’m using this to track usage of hundreds of buttons, therefore the code can look really messy if I stick to use my current script.
How would I go about and make this simpler and cleaner?
function clickCounter1() {
if (typeof (Storage) !== "undefined") {
if (localStorage.clickcount1) {
localStorage.clickcount1 = Number(localStorage.clickcount1) + 1;
} else {
localStorage.clickcount1 = 1;
}
document.getElementById("result1").innerHTML = "Btn 1: " + localStorage.clickcount1;
}
}
function clickCounter2() {
if (typeof (Storage) !== "undefined") {
if (localStorage.clickcount2) {
localStorage.clickcount2 = Number(localStorage.clickcount2) + 1;
} else {
localStorage.clickcount2 = 1;
}
document.getElementById("result2").innerHTML = "Btn 1: " + localStorage.clickcount2;
}
}
function clickCounter3() {
if (typeof (Storage) !== "undefined") {
if (localStorage.clickcount3) {
localStorage.clickcount3 = Number(localStorage.clickcount3) + 1;
} else {
localStorage.clickcount3 = 1;
}
document.getElementById("result3").innerHTML = "Btn 1: " + localStorage.clickcount3;
}
}
<button onclick="clickCounter1()" type="button">Click me!</button>
<button onclick="clickCounter2()" type="button">Click me!</button>
<button onclick="clickCounter3()" type="button">Click me!</button>
<br>
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
Important functions are just two:
- Count the clicks for each button
- Store in local storage
Thank you very much in advance!