Trigger Callback After Clicking N Times
I'm new in Javascript and I can't find the answer for my question. Is it possible that my javascript shows a div after if you clicked on a button 5 times? If this is the case, how
Solution 1:
Without jQuery:
document.addEventListener("DOMContentLoaded", function(event) {
var button = document.getElementById('click_me');
var elem = document.getElementById('message');
var count = 0;
button.addEventListener('click', function(e) {
e.preventDefault();
count++;
if(count == 5){
elem.style.display = 'block';
}
}, false);
});
#message {
background: #0f0;
display: none;
padding: 10px;
}
<buttontype="button"id="click_me">Click Me</button><divid="message">Hello World</div>
With jQuery:
$(function() {
var count = 0;
$('#click_me').click(function(e) {
e.preventDefault();
count++;
if(count == 5) {
$('#message').show();
}
});
});
#message {
background: #0f0;
display: none;
padding: 10px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><buttontype="button"id="click_me">Click Me</button><divid="message">Hello World</div>
Solution 2:
var clicks = 0;
functionmyFunction() {
clicks = clicks+1;
if(clicks == 5){
document.getElementById('target').style.display = 'block';
}
}
<buttononclick="myFunction()">Click me</button><divstyle="display:none;"id="target">You clicked 5 times</div>
Solution 3:
Do you need like this?
<!DOCTYPE html><html><head><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script><script>
$(document).ready(function(){
n=1;
$(".clickable").click(function(){
if(n==5){
alert("You clicked 5 times");
}else{
n++;
}
});
});
</script></head><body><buttonclass="clickable">Click here 5 times</button></body></html>
Solution 4:
With a little bit of function composition a general click handler function can be crafted to mimic how a real "dblclick" behaves, but with a custom N amount of clicks.
const buttons = document.querySelectorAll('button')
constonClick = (requiredClicks, timeLimit = 300) => cb => {
let timer;
let clicked = 0;
returne => {
// each time clicked, check if reached the goalif( ++clicked == requiredClicks ){
cb(e)
clicked = 0
}
clearTimeout(timer)
timer = setTimeout(() =>
clicked = 0// reset the number of clicks after a traditional 300ms duration
, timeLimit)
}
}
// bind events to all buttons, by their index, which controls the number of clicks
[...buttons].forEach(
(button, idx) => button.addEventListener( "click", onClick(idx + 1)(callback) )
)
// call this callback after N clicks (depending on the button in the demo)functioncallback(e){
console.clear()
console.log("clicked on button at index", e.target.name)
}
<h2>Click fast:</h2><buttonname='1'>Click once</button><buttonname='2'>Click twice</button><buttonname='3'>Click 3 times</button><buttonname='4'>Click 4 times</button>
Post a Comment for "Trigger Callback After Clicking N Times"