Reputation: 113
I wish to allow this JavaScript Button to show other page (active) only when it was continuously clicked for 10 second. Any help would be highly appreciated. e.g. if it was clicked for less than 10 second, it shouldn't call the function and nothing happens.
function callAnothePage()
{
window.location = "https://www.bbc.com/";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html class="no-js" lang="">
<body>
<button name="buttonClick" class="button" onclick="callAnothePage()"
id="btnMakeCall" >how</button>
</body>
</html>
Upvotes: 1
Views: 157
Reputation: 71
If you want the user to click and hold the button for some time the answer of Shilly is a good solution.
But if you want the user to press the button again and again until the time end, maybe you should use a hit ratio instead.
With hit ratio you could define a good ratio to redirect the user and challenge the user to go over the ratio.
That way the user will click repeatedly in the button over a period of time (10 seconds) and you compare the user hit ratio (times clicked / time) with your defined ratio.
The code is something like the snippet below:
document.addEventListener("DOMContentLoaded", function() {
var button = document.querySelector("button#clickMe");
var clicks = 0;
var hitRateNeeded = 3.2;
var timeInSeconds = 10;
var started = false;
var timeout = null;
button.addEventListener('click', function() {
if (!started) {
started = true;
timeout = setTimeout(function() {
freeze();
clearAttempt();
// do something ...
}, timeInSeconds * 1000);
}
clicks++;
});
function freeze() {
var currentHitRate = clicks / timeInSeconds;
console.log("Current Hit Rate", currentHitRate);
console.log("Passed?", currentHitRate > hitRateNeeded)
}
function clearAttempt() {
clicks = 0;
started = false;
clearTimeout(timeout);
}
});
<button id="clickMe">Click for 10 seconds</button>
Upvotes: 0
Reputation: 8589
The clue is to use onmouseup
and onmousedown
instead of onclick
. That way you can start a timeout when the user clicks and remove it again when they stop clicking.
const button = document.querySelector( 'button' );
let timeout = null;
button.addEventListener( 'mousedown', event => {
timeout = setTimeout(() => {
console.log( '2 sec passed' );
}, 2000 );
});
button.addEventListener( 'mouseup', event => {
if ( timeout ) clearTimeout( timeout );
});
<button>2 sec</button>
Upvotes: 1