On click & hold for a duration alert something - javascript

$('#action').click(function() {
if(setTimeout(function() {}, 1000)) {
alert("Hold");
} else {
alert("Click");
}
})
<!-- begin snippet: js hide: false console: true babel: false -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='action'>Hello</button>
I'm trying to alert Click if i just clicked on the button, And alert Hold if i hold clicking the button for 2s,
The problem is that it always alerts Hold after clicking.
How to fix that And how to count the time of holding the button exactly?

Try the snippet below:
$(document).ready(function() {
var timeoutId = 0;
var functionCalled = false;
$("#btn").on("mousedown", function() {
timeoutId = setTimeout(btnHeld, 2000);
}).bind("mouseup", function(e) {
if (!functionCalled) {
alert('clicked');
}
functionCalled = false;
clearTimeout(timeoutId);
});
function btnHeld() {
functionCalled = true;
alert("hold");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">click</button>

You need to handle the mousedown event, set a timer for two seconds, then cancel that timer in the mouseup event.

Related

Function inside event listener triggers only on it's initialization

var init = true;
$('#btn').on('click', delay(function() {
$('#text').append('click');
init = false;
}, 100));
function delay(fn, ms, enabled = true) {
$('#text').append(init);
// if(init) disable delay
let timer = 0;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(fn.bind(this, ...args), ms || 0);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>
Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation.
The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.
For example, try clicking the trigger button. The init variable value is printed only for the first time.
You are calling the delay function in a wrong way in the click handler. You have to call it like so:
$('#btn').on('click', function () {
delay(function() {
$('#text').append('click');
init = false;
}, 100);
});
You will have to check for the value of init inside the function, like this:
$('#btn').on('click', delay(function() {
if(init) {
$('#text').append('click');
init = false;
}
}, 100));
At the moment I don't know why append is not working but with a little workaround you can obtain what you want. Concatenate the original text and the actual one and use text() to set it again:
var init = true;
$('#btn').on('click', function() {
$('#text').text(init);
setTimeout(myDelay, 5000);
});
function myDelay() {
let originalText = $('#text').text();
init = false;
console.log("init is false");
console.log("original text displayed: " + originalText);
$('#text').text(originalText + " " + init);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id='btn'> TRIGGER </button>
<div id="text"></div>

I want to return false in clicked time is greater than 200 ms

I am developing a youtube player. If user long presses on video, a option panel appears. I want to stop it. Is it possible that I write a query that if my click time is greater than 200ms, return false? I am currently using this code but this is not working.
$('video').on('click', function () {
if(longpress) { // if detect hold, stop onclick function
return false;
};
});
$('video').on('mousedown', function () {
longpress = false; //longpress is false initially
pressTimer = window.setTimeout(function(){
// your code here
longpress = true; //if run hold function, longpress is true
},300)
});
$('video').on('mouseup', function () {
clearTimeout(pressTimer); //clear time on mouseup
});
As #Maxx said, simply declare your variables first
var longpress = false;
var pressTimer;
$('video').on('click', function() {
console.log(longpress)
if (longpress) { // if detect hold, stop onclick function
return false;
};
});
$('video').on('mousedown', function() {
longpress = false; //longpress is false initially
pressTimer = window.setTimeout(function() {
// your code here
longpress = true; //if run hold function, longpress is true
}, 300)
});
$('video').on('mouseup', function() {
clearTimeout(pressTimer); //clear time on mouseup
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video style="width: 100px; height: 100px; background-color: rgb(239, 239, 239);"></video>

Javascript clicked and not been clicked for 4 seconds

I have a question about my code. What I'm trying to do is if a certain button is clicked and it isn't clicked again within 4 seconds, a element will be showed and another element hide. But if it is clicked within 4 seconds, it stays the same and so on. I think I should use SetInterval() and ClearInterval(). Currently I have two other functions that do other things. Maybe I can my function there?
Hopefully I have made it clear.
Current javascript code:
var clicks = 0;
function clicks5times() {
clicks = clicks+1;
if(clicks == 6){
document.getElementById('scherm3').style.display = 'block';
document.getElementById('scherm2.2').style.display = 'none';
}
}
var clicked = false;
setInterval(function(){
if (!clicked) {
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
}
},13000);
document.getElementById("buttontimer").addEventListener("click", function(){
clicked = true;
});
Rather than set interval, I would say a timer would be better. Eg:
var clickTimer;
function startTimer() {
clickTimer = window.setTimeout(function(){
document.getElementById("scherm4").style.visibility = "visible";
document.getElementById("scherm2.2").style.visibility = "hidden";
},4000);
}
function stopTimer() {
window.clearTimeout(clickTimer);
}
function restartTimer() {
stopTimer();
startTimer();
}
document.getElementById("buttontimer").addEventListener("click", function(){
restartTimer();
});
This way when you want to stop the timer or start the timer, you have to just call above functions for other scenarios.
eg:
If you have an init function:
function init() {
...
//some code
startTimer();
}
And maybe call stop timer like so:
function clicks5times() {
...
stopTimer();
}
Split your event handlers in two different functions (eg firstClick and secondClick). The first handler should just add a second event listener and remove it after 4 seconds. For this one-off task, use setTimeout instead of setInterval as you need the task to be done only once after 4 seconds and not every 4 seconds. So I would proceed as follows:
var secondClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE SECOND CLICK
}
var firstClick = function() {
// DO WHATEVER YOU WANT TO HAPPEN AFTER THE FIRST CLICK
document.getElementById("buttontimer").addEventListener("click", secondClick);
setTimeout(function() {
document.getElementById("buttontimer").removeEventListener("click", secondClick);
}, 4000);
};
buttonElement.addEventListener("click", firstClick);
in Javascript
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<button id="buttontimer">fghfgh</button>
<script>
document.getElementById('buttontimer').onclick = function(){
document.getElementById("buttontimer").disabled=true;
setInterval(function(){
if (document.getElementById("buttontimer").disabled == true) {
document.getElementById("buttontimer").disabled = false;
}
},10000);
};
</script>
</body>
</html>
and Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var button = $('<button>Click Me</button>');
button.clicked = false;
$('body').append(button);
var clicked = false;
button.click(function(){
button.clicked = true;
button.prop('disabled', true);
clicked = true
setInterval(function(){
if (clicked) {
button.prop('disabled', false);
}
},10000);
});
});
</script>
</head>
<body>
</body>
</html>
once u click button disable the property after the timer finish enable back the property

On / Off function after a certain period of time

Wondering how you can make .off() only happen for a specific period of time. I have a div which once clicked i want to disable the click event for 2 seconds, and then be allowed to click again. At the moment all I have is the div can be clicked, then once clicked it is off.
Here is a brief example of what I am asking:
$('.test').on('click', function() {
// *do stuff*
$('.test').off('click'); *for a certain perdiod of time*
});
It's a much simpler task to use a boolean variable as a flag to state whether the click handler should be executed, instead of attaching/detaching events from multiple elements. Try this:
var clickEnabled = true;
$('div').click(function() {
clickEnabled = false;
setTimeout(function() {
clickEnabled = true;
}, 2000);
});
$('.test').on('click', function(e) {
if (!clickEnabled) {
e.preventDefault();
} else {
// do stuff...
}
});
Note that you should also make the fact that .test is disabled visible in the UI, otherwise you'll just confuse and annoy your visitors when they click an element expecting an action, but nothing happens.
What about activate on after a certain period of time?
function myFunction() {
...do stuff
$('.test').off('click'); for a certain perdiod of time
setTimeout(function(){ $('.test').on('click', myFunction)}, 2000);
}
Using the setTimeout you may do something like:
var enabled = true;
var timeoutSeconds = 2;
$(function () {
$('.test').on('click', function(e) {
if (enabled) {
// *do stuff*
enabled = false;
window.setTimeout(function() {
enabled = true;
}, timeoutSeconds * 1000);
} else {
e.preventDefault();
}
});
});
You could do it like this.
function onClick() {
// do stuff here
$('.test').off('click');
setTimeout(function(){
$('.test').on('click', onClick);
}, 2000)
}
$('.test').on('click', onClick);
Or you can do it with css and toggleClass
// css
.disabled {
pointer-events: none;
}
// js
$('.test').on('click', function(){
// do stuff here
$('.test').addClass('disabled');
setTimeout(function(){
$('.test').removeClass('disabled');
}, 2000);
});

Adding a timed delay after pressing a button to prevent button spam

Say I have 4 buttons
<button id="one">One</button>
<button id="two">Two</button>
<button id="three">Three</button>
<button id="four">Four</button>
and to prevent spam, I want to make it so that whenever any of the buttons are pressed, none of them are able to be pressed again for the next 0.6 seconds.
How might I achieve this?
You can use this javascript code:
var btns = document.getElementsByTagName('button');
for(var i=0;i<btns.length;i++){
btns[i].addEventListener('click', function(){
disableButtons(true);
setTimeout(function(){disableButtons(false);}, 600);
});
}
function disableButtons(state){
for(var i=0;i<btns.length;i++){
btns[i].disabled = !!state;
}
}
Of course, you need to run this code after your page is loaded.
One way to do this is with a "click shield".
Here's how you can do it with jQuery.
var clickShield = false;
$('button').on('click', function() {
if (!clickShield) {
clickShield = true;
console.log('handle click event');
setTimeout(function() {
clickShield = false;
}, 600);
}
});
With jQuery you can do something like:
<button id="one">One</button>
<button id="two">Two</button>
<button id="three">Three</button>
<button id="four">Four</button>
$("button").on("click", function(e) {
$("button").attr('disabled', 'disabled');
setTimeout(function() {
$("button").removeAttr('disabled');
}, 600);
});
// Get button elements
var els = document.getElementByTagName('button');
// Add an event handler to click event
// that triggers settimeout to set the disable value
els.addListener('click', function(){
setTimeout(els.disable, 600);
}, true);
not tested
Like prasadmadanayake says in his comment you can do it by disable/enable the button.
Here is a working example:
var intVal = 0;
$('button').on('click',function (e) {
var id = $(this).attr('id');
$('#'+id).attr('disabled', 'disabled');
setTimeout(function(){enable(id)}, 3000);
return true;
});
function enable (id) {
$('#'+id).removeAttr('disabled');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="one">One</button>
<button id="two">Two</button>
<button id="three">Three</button>
<button id="four">Four</button>

Categories

Resources