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;
}
<button type="button" id="click_me">Click Me</button>
<div id="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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="click_me">Click Me</button>
<div id="message">Hello World</div>
Solution 2:
var clicks = 0;
function myFunction() {
clicks = clicks+1;
if(clicks == 5){
document.getElementById('target').style.display = 'block';
}
}
<button onclick="myFunction()">Click me</button>
<div style="display:none;" id="target">You clicked 5 times</div>
Solution 3:
Do you need like this?
<!DOCTYPE html>
<html>
<head>
<script src="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>
<button class="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')
const onClick = (requiredClicks, timeLimit = 300) => cb => {
let timer;
let clicked = 0;
return e => {
// each time clicked, check if reached the goal
if( ++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)
function callback(e){
console.clear()
console.log("clicked on button at index", e.target.name)
}
<h2>Click fast:</h2>
<button name='1'>Click once</button>
<button name='2'>Click twice</button>
<button name='3'>Click 3 times</button>
<button name='4'>Click 4 times</button>
Post a Comment for "Trigger Callback After Clicking N Times"