OK so I am making a reaction tester, and I have a function that makes shapes appear on screen, So what I want is some sort of function were after 5 clicks on a certain element it will end a function. Is there a way of doing that? sorry if its a dumb question, its because I am new to the whole coding...
Asked
Active
Viewed 1,797 times
0
-
What do you mean "end function"? Executing a function after five clicks on a certain element? – Samuli Hakoniemi Jan 09 '15 at 10:09
-
Yes, there is a way to do that, it's called counting. Use a variable that is incremented on each click. – adeneo Jan 09 '15 at 10:09
-
use a static variable using a closure to count the number of times a function is executed and if it's greater than, say 5 just return. – Ehtesham Jan 09 '15 at 10:12
-
What I mean is I have a div that on each clicks starts a function what i want it to do after 5 clicks on that div stop the function – John Smith Jan 09 '15 at 10:13
4 Answers
1
Here you go
var clickHandler = (function (e) {
var count = 0;
return function () {
count += 1;
if (count > 5) {
return;
}
// do other stuff here
}
}());
aDiv.addEventListener('click', clickHandler, false);

Ehtesham
- 2,967
- 1
- 18
- 20
0
You may use global variable which may remain counting on click function
<script>
var globalvar = 0;
onclickfunct()
{
globalvar += 1;
if(globalvar == 5)
{
//do my work
}
else
{
//give alert
}
}
</script>

Akash kumar
- 981
- 3
- 14
- 27
-
-
you may stop based on variable value, suppose you want 5 click just use if condition and limit it to 5, place your code inside. – Akash kumar Jan 09 '15 at 10:17
-
yes, inside if condition you may place your code u want to perform on click – Akash kumar Jan 09 '15 at 10:26
-
0
You can unbind the click event once the counter reaches 5. See the example below
function test(sender) {
sender.dataset.clicked++;
console.log("I've been clicked", sender.dataset.clicked);
if (+sender.dataset.clicked === 5) {
// unbind the event
sender.onclick = null;
}
return;
}
<div onclick="test(this);" data-clicked="0">click me</div>

Peter Flannery
- 2,061
- 1
- 16
- 5