Reputation: 35
I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on! any response is appreciated!
Upvotes: 0
Views: 2433
Reputation: 1090
Use this Code
HTML:
<button type='button' id='button_test_clicks'>
Click me!
</button>
JavaScript:
(function(){
var counter=0; // counter clicks initialization
var button=document.getElementById('button_test_clicks'); //Our button
button.addEventListener("click",function(){ //add a click event to button
counter++; //incement the counter
console.log(a);
if(counter==5){
button.style.display = 'none'; //hide if the clicks reached to 5
}
});
})();
But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage
in javascript.
Upvotes: 1
Reputation: 41
I made a small example with jQuery
var count = 0;
$("#b1").click(function() {
count++;
if (count >= 5) {
$("#b1").hide();
}
});
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<button id="b1">5 Clicks</button>
</body>
</html>
Upvotes: 0
Reputation: 6403
Assign id
to your button.
<Button id='myButton' onclick="myFunction()">
On every click of button, keep incrementing the counter (I think you know how to do it)
After the counter is reached,
document.getElementById("Your_button_id_here").style.visibility = "hidden";
<script>
var counter=0;
function myFunction() {
//increment counter
counter+=1;
if(counter>4)
document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>
However, I think disabling would be more proper:
document.getElementById("Your_button_id_here").disabled=true
Upvotes: 0
Reputation: 1247
On every click just increment a variable's value and after got desired number, hide it by css and js.
Upvotes: 0
Reputation: 78
You could have a simple script like this :
var nbClicks=0;
function btnOnClick(btn){
if(++nbClicks>5){btn.style.display='none';}
}
And use it like that : <input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">
Upvotes: 0