How can I check how long a click was held? - javascript

I'm firing an onClick event and would like to somehow check if it was just a click or if it was held down for some time before releasing mouse button and actually firing a click event.
reason for this is to either perform a myTest() function so onClick="myTest()" that simply console logs either "mouse was clicked" or "mouse was held and clicked" depending on what action user performs.

You should do below code:
var timeout, clicker = $('#clicker');
var count = 0;
clicker.mousedown(function(){
timeout = setInterval(function(){
clicker.text(count++);
}, 500);
return false;
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
You can hold the mouse on the square and the enter code here count interval is 500 miliseconds.
you can change it as per your requirements
Hope this will help you.

Related

Toggled boolean variable evaluated in conditional statement on click event

I am toggling the boolean variable "userTurn". There are two functions that set the value of "userTurn":
runGame(), which sets "userTurn" to true after the last sound in the current round is played.
buttonClick(), which should only be executed if "userTurn" is true. buttonClick sets "userTurn" to false after the user successfully copies the current pattern, or if the user makes a mistake.
I am evaluating the value of "userTurn" in a conditional statement that is inside of a click event.
$(".quarter").on('click', function(){
if( userTurn===true && isOn===true){
var color = $(this).attr('id');
clearTimeout(buzz);
buttonClick(color);
}
})
After the user successfully copies the current pattern, or if the user makes a mistake, "userTurn" is set to false. The problem I am running into is, after "userTurn" is set to false, the code inside the conditional statement is still executing. The goal is for ".quarter" to only be clickable when "userTurn" is true. Why is the buttonClick() function still executing when ".quarter" is clicked even when "userTurn" is false??
Here are the two functions that set the value of "userTurn":
runGame():
function runGame(){
if(isOn===true){
userTurn = false;
count();
playPattern(order, index);
if(index===counter-1&&userTurn===false){
userTurn=true;
clearInterval(play);
buzz = setTimeout(buzzer, 10000);
}else{
index++;
}
} else {
clearInterval(play);
clearTimeout(buzz);
}
}
2.buttonClick():
function buttonClick(color){
var yellowSound = document.getElementById("horseSound");
var redSound = document.getElementById("endFx");
var greenSound = document.getElementById("westernRicochet");
var blueSound = document.getElementById("robotBlip");
$("#red").mousedown(function(){
$("#red").css("background-color", "#ff4d4d");
redSound.play();
});
$("#red").mouseup(function(){
$("#red").css("background-color", "#ff0000");
redSound.pause();
});
$("#blue").mousedown(function(){
$("#blue").css("background-color", "#0000e6");
blueSound.play();
});
$("#blue").mouseup(function(){
$("#blue").css("background-color", "#000099");
blueSound.pause();
});
$("#green").mousedown(function(){
$("#green").css("background-color", "#00e600");
greenSound.play();
});
$("#green").mouseup(function(){
$("#green").css("background-color", "#009900");
greenSound.pause();
});
$("#yellow").mousedown(function(){
$("#yellow").css("background-color", "#ffff4d");
yellowSound.play();
});
$("#yellow").mouseup(function(){
$("#yellow").css("background-color", "#ffff00");
yellowSound.pause();
});
if(color===order[compareIndex]){
userPattern.push(color);
console.log(userPattern, "match");
buzz = setTimeout(buzzer, 10000);
compareIndex++;
if(userPattern.length===counter){
userTurn=false;
compareIndex=0;
index=0;
counter++;
count();
userPattern.length=0;
play = setInterval(runGame, 2000);
clearTimeout(buzz);
}
} else {
userTurn=false;
console.log('don\'t match');
clearTimeout(buzz);
index=0;
compareIndex = 0;
userPattern.length=0;
buzz = setTimeout(buzzer, 1);
}
}
TURN DOWN YOUR VOLUME BEFORE GOING TO THE CODEPEN!!
Here is a link to the codepen.
To start the game click "On Off" and then click "start". The timing is slow so you have to wait for the pattern to play, then click the buttons in the same order as they were played. The problem is seen after the first sound is played. From that point on any click the user makes will play the sound and light up the button, even when the game is playing the pattern and "userTurn" is false. Also be warned, this is still a work in progress, there are a couple of other bugs I'm working on, for example the the first turn the user makes will not light up or play the sound, but the selection is pushed into the correct array and the game will proceed properly based on your selection. I know this is a lot of info but I'm stuck on this so any feed back will be very appreciated. Thanks!
You're using buttonClick to handle clicking the buttons, but inside buttonClick you're setting mouseup and mousedown event listeners for each button as well. Since the individual buttons have their own mouseup and mousedown listeners, the events will happen whether or not buttonClick is called again.
You would have to check if userTurn is true inside of each of those event handlers as well to prevent them from triggering. Also, it would better to set these outside of buttonClick so you won't be adding new listeners every time buttonClick gets called.

How can I stop triggering click event after the first trigger?

Using a triggered click on my website (Its not on the website not due to the bug).
Website: 3six-d.co.uk
setTimeout(function() {
$('a[href$="#about"]').trigger('click');
}, 5000);
However as you could possible guess, that works fine. Until someone click the Enter button faster than 5 seconds, and they goes to a different tab. Say I clicked enter then went to the contact form. After the 5 seconds it would then redirect me back to about us. If there a way that if the user has already clicked enter it stops the trigger?
Thanks
You can try this
var isClicked = false;
setTimeout(function() {
if (!isClicked) {
isClicked = true;
$('a[href$="#about"]').trigger('click');
}
}, 5000);
With the former approach you guarantee that the click is only triggered once. No matter how often the user clicks.
How about a global Boolean variable that is set to true once the trigger is clicked? If the global Boolean is true, it does not allow the trigger event to run again. And, when the global is set to true, another timer is started that resets it to false after five or six seconds?
Detect when a user click the "Enter" button (look this up, its easy) then clear the timeouts using:
var id = window.setTimeout(function() {}, 0);
while (id--) {
window.clearTimeout(id);
}

Fire event when user stops to click

I'm able to detect a click on a button using jQuery
$('#myButton').click(function(){
// do something
});
but, when the user clicks many times on the button, it fires unnecessary intermediaries events.
I would like to fire the event only on the last click on the button.
Something like:
$('#myButton').lastClickOnASequenceOfClicks(function(){
// ignore the multiple clicks followed
// do something only on the last click of a sequence of clicks
});
With that, if the user clicks 10 times (with a little interval of time), it should fires an event only on the tenth click.
Each click resets the timer.
var timer;
$("#myButton").click(function () {
var timeToWait = 1000;
clearTimeout(timer);
timer = setTimeout(function () {
// do something only on the last click
}, timeToWait);
}
Update
Another way to solve this problem of handling 'multiple click events' generated by the user is to do what was mentioned in the OP comments section. do something on the first click THEN disable the button so the user cannot click it anymore (maybe also set a time for the button to become enabled again)
var timer, timeToWait = 5000, selector ="#myButton";
$(selector).click(function (e) {
$(this).attr("disabled", "disabled");
// do something
// Then wait a certain amount of time then remove the disabled attr on your button
timer = setTimeout(function () {
$(selector).removeAttr("disabled");
}, timeToWait);
})

Cancel all event except the last one,

Is it possible to do this: suppose that there are a lot of same events fire a lot of times in a period of time, we will cancel all the previous event and only use the last one.
The last event will be for for one time only when there is no more event for 3 seconds.
For example: there is a button; we will let user click this button many times as they want and we will not disable this button. No matter how many times user have been clicking this we will consider it to be only one click count as the last click. The click event will be performed when there are no more clicks within 3 seconds.
What you are looking for is known as debouncing. For this task there is already a superb plugin/library from Ben Alman.
(function() {
var button = document.getElementsByTagName("button")[0],
func = Cowboy.debounce(1000, function() { console.log("click fired!"); });
button.addEventListener("click", func);
}())​
fiddle
var domButton = document.getElementById('some-button'),
timeOut;
domButton.addEventListener('click', function(e) {
if (e.clientX && e.clientY) {
e.preventDefault();
clearTimeout(timeOut);
timeOut=setTimeout(function({document.getElementById('somebutton').click()},3000);
}
},false)

Display DIV only if user has been Idle for X amount of time

I would like to display a helpful DIV that basically shows the user how to accomplish something on a particular page, but only if the user has been idle for a period of time, say, 30seconds.
What I mean by "Idle" is:
Not clicking any links
Not right clicking anywhere
Exceptions:
I would like to exclude the following conditions from the Is User Idle rule:
User has scrolled up or down/left or right
User has pressed mouse button on an empty area on the site/ or on an element which has no source/link for example, an image with no hyperlink.
and, Pressing keyboard buttons
Can this be done? Or can we only detect when a particullar event occurs?
Any thoughts/suggestions/resources will be greatly appreciated.
Thank you
fairly basic...
var trigger = 30000
$.(function(){
setInterval('displayInf()',trigger );
$('body').bind('click dblclick keypress mousemove scroll', function(){
clearDisplayInf();
});
});
function displayInf()
{
$('body').append('<div>Your notification div</div>');
}
function clearDisplayInf()
{
trigger = clearInterval(trigger);
trigger = setInterval('displayInf()', 30000 );
}
that should do the trick - you could add some script to make the div removable and start the timer again once its removed but that just polishing up really..
Event in DOM would bubble from leaf to root, thus add a event listener on document would make sense.
But since we are possibiliy stop bubbling for click event in certain element, register click event on document may not work perfectly, in that case, register mousedown and mouseup event would help:
var timer; // create a timer at first
// restart timer on click
function startIdle() {
timer = setTimeout(function() { /* show div */ }, time);
}
if (document.addEventListener) {
document.addEventListener('mouseup', startIdle, false);
}
else {
document.attachEvent('onmouseup', startIdle);
}
// start the first timer
startIdle();

Categories

Resources