I have two event handlers, one for keydown and one for keyup. The keydown event handler triggers an alert message, but this prevents the keyup event from firing.
You can see a very simple example here: http://jsfiddle.net/boblauer/jaGwT/ When the keydown opens an alert, the keyup is not fired, but when an alert is not opened, the keyup is fired. Here's the code from the jsfiddle:
var i = 0;
window.addEventListener('keydown', function(e) {
if (i++ % 2) alert('down');
console.log('down');
});
window.addEventListener('keyup', function(e) {
alert('up');
console.log('up');
});
I have a library that supports listening to multiple key combinations (such as 'd + f'), so when a key is pressed, I need to add it to a list of keys that are currently pressed, and when a key is released, I need to remove it from said list. The problem I'm running to is, if I want an alert to show when d + f are pressed at the same time, my code to remove those keys from the 'currently pressed' list never fires, because my keyup handler is never called.
I can't think of a good work around to this problem. Any ideas?
The alert prevents the event from happening. What you could do instead is trigger this function manually, because it happens anyways.
var keyupfunction = function(e){
alert('up');
console.log('up');
}
window.addEventListener('keyup', keyupfunction);
window.addEventListener('keydown', function(e) {
if (i++ % 2) alert('down');
console.log('down');
keyupfunction(e);
});
But really, you shouldn't be using alerts. It prevents these events, but who knows what else it might break. Use something custom instead.
Related
So I have a plugin (sort of lightbox/tour/gallery) which runs with the click of a button, and when the button has been click the user can navigate thru the plugin with the use of the keyboard keys(left and right for prev/next) but when the plugin comes to the end(last image) and the user keeps on pushing the right arrow key when the user clicks the button and the plugin runs again the previous registered key presses will be fired.
Is there a way to clear all registered keypresses like cleaning the chache?
// keydown part
$('body').on('keydown', function(e){
/**
* Space key.
**/
if(e.keyCode == 32){
//run code
}
/**
* Arrow left key.
**/
if(e.keyCode == 37){
//run code
}
/**
* Arrow right key.
**/
if(e.keyCode == 39){
//run code
}
});
As you correctly used on() to attach the event handler, you can use off() to detach it. If you do not pass a function to it, it will remove all event handlers for that event:
$("body").off( "keydown" );
As you are doing this on the <body> tho, this is a bit heavy-handed, as you may end up removing other keypress handlers which aren't part of your plugin. A better option would be to pass the specific function to off() so you only remove that handler. You can structure it something like this:
// IIFE to encapsulate plugin variables
(function() {
function keyDownHandler(e) {
if(e.keyCode == 39) {
// code...
}
}
// attach the handler
body.on('keydown', keyDownHandler);
// some function to handle moving through the carousel
function showImage() {
if(endOfCarousel) {
// remove the handler
body.off('keydown', keyDownHandler);
}
}
})();
By the way unbind() mentioned in the other answers is used for events attached with bind(), and is less preferred.
You are using Jquery
It has some function to bind or unbind events
It requires the event name, which you want to unsubscribe.
I would advice to have a look at this link for better understanding.
You may use it something like this
if(end of the carosel){
$(this).unbind(your desired event)
}
Try this:
$( "#body").unbind( "keydown" );
Official documentation
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.
Is anybody else having problems with the keyup event in iOS 9 not firing?
Just a simple test bed replicates the issue for me.
<input id="txtInput" />
Vanilla JS:
document.getElementById('txtInput').onkeyup = function () {
console.log('keyup triggered');
}
jQuery:
$('#txtInput').on('keyup', function () {
console.log('keyup triggered');
});
Neither fire...
I suggest using the keypress event on browsers with touch screens. I know that you can't really detect touch screen screens, though, so it leaves you with a few options that your situation will likely dictate.
Attach both events keyup and keypress. This would likely be dependent on how much processing is going on and if you are getting double-fires in some browsers.
Attempt to determine whether the browser is a touch screen (like using Modernizr), and then attach a fallback handler like change.
Either way, you end up with two event listeners.
$('#yourid').bind('keypress', function(e) {
// This will work
});
It's not pretty, but a work around is to bind to keydown to capture which key has been pressed, and input if you want to obtain the value, including the key typed:
(function () {
var keyCode;
$('#txtInput')
.on('keydown', function (e) {
// value not updated yet
keyCode = e.keyCode;
// Enter key does not trigger 'input' events; manually trigger it
if (e.keyCode === 13) $(this).trigger('input');
})
.on('input', function (e) {
console.log(keyCode, this.value);
});
}());
If you type 'a' the following occurs:
keydown fires.
e.keyCode is set to the ASCII value of the key pressed.
this.value is '' (i.e. the same before 'a' has been typed).
input fires.
e.keyCode is undefined.
this.value is 'a'.
You can also manually trigger an input event if the enter (13) key is pressed; input isn't fired by this key by default.
Here's a JSFiddle of the behavior I'm seeing, relating to middle-click and the click event in Chrome and FF.
'click' kinda sorta works
Approach 1: Bind a click handler directly to an a element and a middle-click will trigger the handler in Chrome but not in FF.
$('div a').on('click', function(ev) {
// middle click triggers this handler
});
Approach 2: Bind a delegated click handler to a div which contains one or more a. Middle click will not trigger this handler in Chrome or FF.
$('div').on('click', 'a', function(ev) {
// middle click doesn't trigger this handler
});
This approach is extremely valuable if the div starts out empty and the a elements are filled in later by an AJAX call, or as a result of some user input.
'mouseup' works
Using mouseup instead of click causes both approach 1 and 2 to work in both browsers.
// Approach 1 w/ mouseup
$('div a').on('mouseup', function(ev) {
// middle click **does** trigger this handler in Chrome and FF
});
// Approach 2 w/ mouseup
$('div').on('mouseup', 'a', function(ev) {
// middle click **does** trigger this handler in Chrome and FF
});
Here's the JSFiddle with mouseup.
This is interesting and might be useful in some cases, because mouseup is almost click. But mouseup isn't click, and I'm after the behavior of click. I do not want to create a hacky mousedown; setTimeout; mouseup simulation of click.
I'm pretty sure the answer is "nope", but is there a cross-browser way to cause middle-click to trigger click handlers? If not, what are the reasons why?
The click event is generally fired for the left mouse button, however, depending on the browser, the click event may or may not occur for the right and/or middle button.
In Internet Explorer and Firefox the click event is not fired for the right or middle buttons.
Therefore, we cannot reliably use the click event for event handlers on the middle or right button.
Instead, to distinguish between the mouse buttons we have to use the mousedown and mouseup events as most browsers do fire mousedown and mouseup events for any mouse button.
in Firefox and Chrome event.which should contain a number indicating what mouse button was pressed (1 is left, 2 is middle, 3 is right).
In Internet Explorer on the other hand, event.button indicates what mouse button was clicked (1 is left, 4 is middle, 2 is right);
event.button should also work in Firefox and other browsers, but the numbers can be slightly different (0 is left, 1 is middle, 2 is right).
So to put that together we usually do something like this :
document.onmousedown = function(e) {
var evt = e==null ? event : e;
if (evt.which) { // if e.which, use 2 for middle button
if (evt.which === 2) {
// middle button clicked
}
} else if (evt.button) { // and if e.button, use 4
if (evt.button === 4) {
// middle button clicked
}
}
}
As jQuery normalizes event.which, you should only have to use that in jQuery event handlers, and as such be doing:
$('div a').on('mousedown', function(e) {
if (e.which === 2) {
// middle button clicked
}
});
In other words you can't use the onclick event, so to simulate it you can use both mousedown and mouseup.
You can add a timer to limit the time allowed between the mousedown and mouseup event, or even throw in a mousemove handler to limit the movement between a mousedown and mouseup event, and make the event handler not fire if the mouse pointer moved more than ten pixels etc. the possibilites are almost endless, so that shouldn't really be an issue.
$('#test').on({
mousedown: function(e) {
if (e.which === 2) {
$(this).data('down', true);
}
},
mouseup: function(e) {
if (e.which === 2 && $(this).data('down')) {
alert('middle button clicked');
$(this).data('down', false);
}
}
});
Short answer: Nope.
The question is, what do you want to capture the middle clicks for? A middle click isn't meant to interact with the current page but rather to open a link in a new tab.
Chrome is also currently working on droping this behavior: https://code.google.com/p/chromium/issues/detail?id=255
And there is currently a general discussion on the w3c mailing list about this topic: http://lists.w3.org/Archives/Public/www-dom/2013JulSep/0203.html
Yet for now, you can catch middleclicks in Firefox on a document-level:
$(document).on('click', function(e){
console.log(e);
});
I've build a factory for creating Middle mouse click handlers using vanilla JS and working in latest Firefox and Chrome:
const MiddleClickHandlerFactory = (node, handlerFn) => {
node.addEventListener('mousedown', e => {
if (e.button !== 1) return;
e.preventDefault(); // stop default scrolling crap! Instead install ScrollAnywhere!
const originalTarget = e.target;
document.addEventListener('mouseup', e => { // register on DOCUMENT to be sure it will fire even if we release it somewhere else
if (e.target.isSameNode(originalTarget)) handlerFn(e);
}, {capture: true, once: true, passive: true});
}, true)
};
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 );
});