To do this you can add the element a specific class name which is "alreadyClicked" in this snippet after that you can check the element has this class or not with the hasClass()
function that I share below.
function myFunction() {
if(hasClass(document.getElementById('money'),'alreadyClicked')){
console.log("button was already clicked");
}
else {
console.log("First click, added to class: alreadyClicked to element");
document.getElementById('money').classList.add("alreadyClicked");
}
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button id="money" onClick="myFunction()"> £25 </button>
Another solution is using a new attribute with the same logic. You can add an attribute your element like data-clicked="false"
. According to Mozilla explained here;
Any attribute on any element whose attribute name starts with data- is
a data attribute. Say you have an article and you want to store some
extra information that doesn’t have any visual representation. Just
use data attributes for that.
<button
id="money"
data-clicked="true"
data-clicked-count="3">
£25</button>
To reach the data attributes with Javascript you can use below snippet.
var element = document.getElementById('money');
element.dataset.clicked; // true
element.dataset.clickedCount; // 3
And also you can set them more easily than class name updating and checking.
var element = document.getElementById('money');
element.dataset.clickedCount = 4
Full Solution with Data Attr
function myFunction() {
const myButton = document.querySelector('#money');
if(myButton.dataset.clicked == 'false'){
myButton.dataset.clicked = 'true';
console.log("data-clicked updated!");
}
myButton.dataset.clickedCount = parseInt(myButton.dataset.clickedCount)+1;
console.log("count of click : "+myButton.dataset.clickedCount);
}
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
<button
id="money"
onClick="myFunction()"
data-clicked='false'
data-clicked-count='0'>
£25
</button>