Not exiting first keypress event when parent function gets fired - javascript

Problem
I have a .keypress() event inside of a .click() event. The first time the user clicks on the element, everything works fine, but subsequent clicks trigger the .keypress() event again without "closing" the first one. I've tried adding event.cancelBubble = true; and an empty return statement to break out of the function, but it hasn't worked because predictably, the rest of the code in that execution doesn't get executed but the event is still active and a key press could still trigger it. Is there a way to close the .keypress() event when foo gets clicked?
Code
$(foo).click(function(){
//Do stuff
$(foo).keypress(function(event) {
//Do stuff
});
});

do you mean keypress called more than once?
in your code, every time you click foo, a new anonymous function will be added to keypress event.
unbind the previous keypress event handler before binding new handler
$(foo).click(function(){
//Do stuff
$(foo).off('keypress').on('keypress', function(event) {
//Do stuff
});
});

I'm not entirely sure what you're asking but I think you want to turn off the keypress after the first click. This should toggle it though you may want to make the pressed var global; maybe.
$(foo).click(function(){
//Do stuff
var pressed = false;
$(foo).keypress(function(event) {
if(!pressed){
//Do stuff
pressed = true;
} else {
event.off();
pressed = false;
}
});
});
The key here is event.off() which will remove the listener.

Related

setTimeout and event propagation

I want to create a one-time event triggered by clicking anywhere. This event is created by clicking a button. I do not want the event to trigger upon clicking the button, only any subsequent clicks anywhere (including the button).
So say I've got some html like the following:
<body>
<div id="someparent">
<div id="btn"></div>
</div>
</body>
And the following javascript (jquery):
$('#btn').click( function() {
$(document).one('click', function() {
console.log('triggered');
});
});
$('#someparent').click(function() {
// this must always be triggered
});
I want to avoid stopping event propagation, but in the above example, the event is bound to document, the event then bubbles up, and the event is triggered.
One way to fix this seems to be to wrap the event creation in a timeout:
$('#btn').click( function() {
setTimeout(function() {
$(document).one('click', function() {
console.log('triggered');
});
}, 1);
});
$('#someparent').click(function() {
// this must always be triggered
});
Now, this works fine, but I'm wondering whether this is safe. Does some notion of order of execution guarantee that this will always work, or is it just working by chance? I know there are other solutions (another nested .one() event for instance), but I'm specifically looking for an answer to how setTimeout and event propagation interoperates.
The following fiddle shows two divs. The first one has the wrong behaviour (the document event is triggered immediately). Clicking the second div, and then anywhere on document (white area) illustrates the wanted behaviour:
https://jsfiddle.net/Lwocuuf8/7/
Event bubbling means that, after an event triggers on the deepest possible element, it then triggers on parents in nesting order.
From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Adding_messages
Adding messages
In web browsers, messages are added any time an event occurs and there
is an event listener attached to it. If there is no listener, the
event is lost. So a click on an element with a click event handler
will add a message--likewise with any other event.
Calling setTimeout will add a message to the queue after the time
passed as second argument. If there is no other message in the queue,
the message is processed right away; however, if there are messages,
the setTimeout message will have to wait for other messages to be
processed. For that reason the second argument indicates a minimum
time and not a guaranteed time.
So, the behaviour you have, is not by chance, you are guaranteed that the messages in the queue will be processed before processing the message you add after a timeout.
Here is a workaround by using a flag instead of a second event :
var documentWaitingClick = false;
$(function() {
$(document).on('click', function(e) {
if (documentWaitingClick) {
//simulate the "one"
documentWaitingClick = false;
console.log('document click');
} else if (e.target.tagName === 'BUTTON') {
documentWaitingClick = true;
console.log('button click')
}
});
});
My understanding of what you want: after clicking an "activation" button, the next click anywhere on the page (including on the "activation" button) should trigger a special event. This is easily handled with a flag:
var activationFlag = false;
$('#btn').click(function(event){
event.preventDefault();
if(!activationFlag) {
event.stopPropagation();
console.log('Global event activated');
}
activationFlag = true;
});
$('#someparent').click(function(event){
if(activationFlag) {
console.log('Time for a special event');
} else {
event.preventDefault();
event.stopPropagation();
}
});

How to run a function only once when it's triggered by both focus and click events

I have an input element with 2 events attached: focus and click. They both fire off the same helper function.
When I tab to the input, the focus event fires and my helper is run once. No problems there.
When the element already has focus, and I click on it again, the click event fires and my helper runs once. No problems there either.
But when the element does not have focus, and I click on it, BOTH events fire, and my helper is run TWICE. How can I keep this helper only running once?
I saw a couple similar questions on here, but didn't really follow their answers. I also discovered the .live jQuery handler, which seems like it could work if I had it watch a status class. But seems like there should be a simpler way. The .one handler would work, except I need this to work more than once.
Thanks for any help!
The best answer here would be to come up with a design that isn't trying to trigger the same action on two different events that can both occur on the same user action, but since you haven't really explained the overall problem you're coding, we can't really help you with that approach.
One approach is to keep a single event from triggering the same thing twice is to "debounce" the function call and only call the function from a given element if it hasn't been called very recently (e.g. probably from the same user event). You can do this by recording the time of the last firing for this element and only call the function if the time has been longer than some value.
Here's one way you could do that:
function debounceMyFunction() {
var now = new Date().getTime();
var prevTime = $(this).data("prevActionTime");
$(this).data("prevActionTime", now);
// only call my function if we haven't just called it (within the last second)
if (!prevTime || now - prevTime > 1000) {
callMyFunction();
}
}
$(elem).focus(debounceMyFunction).click(debounceMyFunction);
This worked for me:
http://jsfiddle.net/cjmemay/zN8Ns/1/
$('.button').on('mousedown', function(){
$(this).data("mouseDown", true);
});
$('.button').on('mouseup', function(){
$(this).removeData("mouseDown");
});
$('.button').on('focus', function(){
if (!$(this).data("mouseDown"))
$(this).trigger('click.click');
});
$(".button").on('click.click',evHandler);
Which I stole directly from this:
https://stackoverflow.com/a/9440580/264498
You could use a timeout which get's cleared and set. This would introduce a slight delay but ensures only the last event is triggered.
$(function() {
$('#field').on('click focus', function() {
debounce(function() {
// Your code goes here.
console.log('event');
});
});
});
var debounceTimeout;
function debounce(callback) {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(callback, 500);
}
Here's the fiddle http://jsfiddle.net/APEdu/
UPDATE
To address a comment elsewhere about use of a global, you could make the doubleBounceTimeout a collection of timeouts with a key passed in the event handler. Or you could pass the same timeout to any methods handling the same event. This way you could use the same method to handle this for any number of inputs.
Live demo (click).
I'm just simply setting a flag to gate off the click when the element is clicked the first time (focus given). Then, if the element gets focus from tabbing, the flag is also removed so that the first click will work.
var $foo = $('#foo');
var flag = 0;
$foo.click(function() {
if (flag) {
flag = 0;
return false;
}
console.log('clicked');
});
$foo.focus(function() {
flag = 1;
console.log('focused');
});
$(document).keyup(function(e) {
if (e.which === 9) {
var $focused = $('input:focus');
if ($focused.is($foo)) {
flag = 0;
}
}
});
It seems to me that you don't actually need the click handler. It sounds like this event is attached to an element which when clicked gains focus and fires the focus handler. So clicking it is always going to fire your focus handler, so you only need the focus handler.
If this is not the case then unfortunately no, there is no easy way to achieve what you are asking. Adding/removing a class on focus and only firing the click when the class isn't present is about the only way I can think of.
I have it - 2 options
1 - bind the click handler to the element in the focus callback
2 - bind the focus and the click handler to a different class, and use the focus callback to add the click class and use blur to remove the click class
Thanks for the great discussion everybody. Seems like the debouncing solution from #jfriend00, and the mousedown solution from Chris Meyers, are both decent ways to handle it.
I thought some more, and also came up with this solution:
// add focus event
$myInput.focus(function() {
myHelper();
// while focus is active, add click event
setTimeout(function() {
$myInput.click(function() {
myHelper();
});
}, 500); // slight delay seems to be required
});
// when we lose focus, unbind click event
$myInput.blur(function() {
$myInput.off('click');
});
But seems like those others are slightly more elegant. I especially like Chris' because it doesn't involve dealing with the timing.
Thanks again!!
Improving on #Christopher Meyers solution.
Some intro: Before the click event fires, 2 events are preceding it, mousedown & mouseup, if the mousedown is fired, we know that probably the mouseup will fire.
Therefore we probably wouldn't like that the focus event handler would execute its action. One scenario in which the mouseup wouldn't fire is if the user starts clicking the button then drags the cursor away, for that we use the blur event.
let mousedown = false;
const onMousedown = () => {
mousedown = true;
};
const onMouseup = () => {
mousedown = false;
// perform action
};
const onFocus = () => {
if (mousedown) return;
// perform action
};
const onBlur = () => {
mousedown = false;
// perform action if wanted
};
The following events would be attached:
const events = [
{ type: 'focus', handler: onFocus },
{ type: 'blur', handler: onBlur },
{ type: 'mousedown', handler: onMousedown },
{ type: 'mouseup', handler: onMouseup }
];

Javascript/Jquery click enable

The following code's else part isnt working, i.e. click is not getting enabled.
if
$("#section1").click(function(event){
return false;
});
else
$("#section1").click(function(event){
return true;
});
So basically, I want to remove the click functionality over a certain div section, which is working fine but while returning the click functionality back it is not working. Any suggestions?
You probably want to remove the click event rather than add another one that returns true.
Try (instead of the else bit):
$('#section1').unbind('click');
You need to unbind the click event. The reason being is if say this block of code gets called 3 times, that is putting 3 event handlers on #selection1 and each time it is clicked all three of those functions are called.
if
$("#section1").unbind('click');
else
$("#section1").bind('click', function(event){
return true;
});
$("#section1").click(function(event){
return false;
});
will disable its functionality
$("#section1").unbind('click')
will remove attached click event and let it do its work
$("#section1").click(function(event){
return false;
});
This will disable the click event from happening, whereas true continues the click event, I'm not sure what you want to achieve but you can use bind to attach an event, like so:
$("#section1").bind('click', function(){
alert('You clicked on it');
});
But to remove a click event, you would use the opposite; unbind.

Simulate keypress with jQuery on form element

I'm trying to simulate a keypress with the below code...
jQuery('input[name=renameCustomForm]').live('keyup', function (e) {
console.log('pressed');
});
jQuery('body').click(function (e) {
console.log(jQuery('input[name=renameCustomForm]'));
var press = jQuery.Event("keypress");
press.which = 13;
jQuery('input[name=renameCustomForm]').trigger(press);
});
I got this code from other posts on SO, but it doesn't work. Anyone know why?
Update
Fixed it... it appears triggering "keypress" doesn't automatically trigger "keyup"
Normally, when a user adds something to an inout field, the following events occur:
keydown (once).
keypress (at least once, additional events uccur while the key is pressed down)
keyup (once)
When a key event is simulated, it's not necessary that all events occur in this order. The event is manually dispatched, so the normal event chain isn't activated.
Hence, if you manually trigger the keypress event, the keyup event won't be fired.
You code will trigger a keypress each time you click anywhere on the page..
For your case it might be better to use the .blur() event of the input box..
jQuery('input[name=renameCustomForm]').live('keyup', function (e) {
console.log('pressed');
}).live('blur', function(){
var self = $(this);
console.log( self );
var press = jQuery.Event("keyup");
press.which = 13;
self.trigger( press );
});

onkeypress() not working

i am trying to catch the keypress event on the window (html page opened with an app which uses gecko engine)
function onkeypress(){
alert("key pressed !")
}
i expect this function to be called whenever any button is clicked, when the focus is on window. But the function is not been called.
Any idea what is going wrong here?
Thanks ...
You should assign that function to an element:
var elem = document.getElementById('id-here');
elem.onkeypress = function(){
alert("key pressed !");
};
You need to set it as the handler on the window object if that's what you're after, like this:
window.onkeypress = function() {
alert("key pressed !")
};
This will capture all keypress events that bubble up (the default behavior, from wherever in the page it happened, with the exception of <iframe>, videos, flash, etc). You can read more about event bubbling here.

Categories

Resources