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)
Related
I'm checking the value of a form field and if the value is more than 5 an alert box pops up. This works, but I've noticed that if I fill in the field 1 time, the alert box can be closed normally. If I then enter a new value, also above 5, I need to close the alert box two times, and three times if I would enter a third value. And so on...
I read several related questions on Stackoverflow, but none seemed to be the same issue or related.
window.onload = function() {
displayField();
};
function displayField() {
jQuery('#groupnumber').change(function() {
var amount5 = jQuery('#groupnumber').val();
if (amount5 > 5) {
alert('Alert message');
}
});
};
//Trigger javascript on leaving field
onblur = "displayField();"
So it "keeps score". If I enter a different value the second time and it is still above 5, I would like the alert box to just show once.
Thanks for any help!
The issue is because you call displayField() every time a blur event occurs which in turn adds another change event handler. Therefore when the next change happens all of those handlers are executed.
You can fix this by attaching your event unobtrusively. This way there will only ever be a single event added when the page loads, and it will fire whenever the selected event occurs on the element.
This does work, but has one disadvantage: if one would enter 78, the alert box shows directly after typing the 7, instead of showing when someone is ready with their input. How can that be avoided?
To mitigate that you could 'debounce' the event so that you only show the alert X milliseconds after typing has ended. You can use setTimeout() to do that:
jQuery(function($) {
var timer;
$('#groupnumber').on('input', function() {
clearTimeout(timer);
timer = setTimeout(function() {
var amount5 = $('#groupnumber').val();
if (amount5 > 5) {
alert('Alert message');
}
}, 200);
}).trigger('input'); // fire the event when the page loads
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" />
Note the aliasing of $ in the document.ready handler. This means you can still use $ within the block to refer to jQuery, making your code slightly less verbose.
You can wrap your window.onload function with setTimeout so user have enough time to enter their number
window.onload = function() {
setTimeout(function(){
displayField();
}, 2000)
};
function displayField() {
jQuery('#groupnumber').change(function() {
var amount5 = jQuery('#groupnumber').val();
if (amount5 > 5) {
alert('Alert message');
}
});
};
//Trigger javascript on leaving field
onblur = "displayField();"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="groupnumber" />
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.
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);
})
I have 2 functions when you click on an item, .click and .dblclick
The problem is, that when you dblclick, it runs the .click function twice.
Is there a way to fix this?
$(".item").click(function() {
if (price[this.id] === 1) {
consoleUpdate("This item is worth " +price[this.id]+ " coin");
}
}
$("#fishItem").unbind("dblclick").bind("dblclick").dblclick(function() {
coins = coins+1;
coinUpdate();
invFish1--;
if (invFish1 === 0) {
$("#fishItem").appendTo("#itemStage");
}
});
Per the jQuery documentation for the dblclick event:
It is inadvisable to bind handlers to both the click and dblclick
events for the same element. The sequence of events triggered varies
from browser to browser, with some receiving two click events before
the dblclick and others only one. Double-click sensitivity (maximum
time between clicks that is detected as a double click) can vary by
operating system and browser, and is often user-configurable.
You want to change your events so that you don't have a .click and .dblclick on the same element.
http://api.jquery.com/dblclick/
var cnt=1;
$( "#target" ).click(function(e) {
if(cnt==1)
{
// action on single click if you dont want anything in in single click then use here
e.preventDefault();
}else{
// work on double click
cnt=1;// again set counter
}
cnt++;
});
reference e.preventDefault();
As others mentioned, you can't really bind both click and double click to the same item. There are, however, workarounds.
One way to handle this would be to handle the click code and then check for double-click:
var lastClickTime = 0;
$(".item").click(function() {
var thisClickTime = (new Date).getTime();
if (thisClickTime - lastClickTime < 500) {
//Double-click
}
else {
//Click
}
lastClickTime = thisClickTime;
});
This code essentially captures a "last click time" and if this click time is less than 500 milliseconds from the last click time, then it fires the double-click code. Otherwise it will fire the click code.
The downside with this is that the click-code will be called first and then the double-click code. Also, you're forcing your users into a 500ms double-click. While this is pretty standard, it's not guaranteed. (Slower clickers may have trouble with this.)
A JSFiddle that demonstrates this technique.
You could improve this code by setting a 500ms timeout for the click code and then cancelling the click event if a double-click is fired. The downside with this is that it will force a 500 ms delay between the click and the "click" code.
A JSFiddle that demonstrates the timeout.
If you don't mind handling one single-click, look at the event object details attribute. It is the number of clicks.
$(".item").click(function(event) {
if (event.details === 1) {
//handle single click
} else if (event.details === 2) {
// handle double click
}
}
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();