jQuery keydown event event data - javascript

I am in the process of upgrading our application's jQuery version from 1.4.2.
I have a chunk of JS, which I don't see why it would work but in fact works in 1.4.2 and not in 1.4.3+
$(document).bind('keydown', 'f3',
function (event) {
alert("f3");
//Do something
});
in jQuery 1.4.2 this WORKS and triggers the event handler only for F3.
When I upgrade to 1.4.3+ the event handler is triggered for any keydown (which I think makes sense).
Does the keydown event know to use the event data and check if the key was pressed?
Can anyone help me clarify if it does or does not, and if not why would this code be working in jQuery 1.4.2?
I checked the release notes and the only thing that changed is added method signatures for the bind and keydown events.

Yes. The event object has all information regarding event. But you need to check for F3 manually using properties such as keyCode and which and such properties.
For example the keyCode for F3 is 114. So you would check it like this:
if(e.keyCode === 114){
//F3 is pressed
}
It might be working for you still because now, the second(optional) argument is eventData to which you're passing 'f3'

Yes you can check for the key property and you should be doing it as follows:
$(document).keydown(function( event ) {
if ( event.which == 114 ) { // 114 is the identifier for F3
//Do some stuff
event.preventDefault();
}
});

Related

Keyup works while keypress doesn't Vanilla JS

I'm kinda re-learning JS and try to make modal windows in vanilla JS. So, my task is to make Escape button work and close modal on hitting it. I found out that when I put 'keypress' event on document, it fails to work, while 'keyup' works okay. I couldn't find exact info on why it is so. I used to use e.KeyCode but found out it is deprecated. So I mainly have 2 questions I couldn't find direct answers to:
why keycode doesn't work?
what is the best way to handle keyboard events in 2021?
Here is the code. Console.log doesn't work. If I change keypress to keyup, everything works.
document.addEventListener('keypress', function (e) {
console.log('Event fired');
if (e.key === "Escape" && !modal.classList.contains('hidden')) {
closeModal();
}
})
Thanks in advance.
Best regards,
Vadim
Like you said "keyCode" is deprecated but it still works (see example below).
The best way in your case would be to use keyup and e.key.
Your code works as expected (with any other key), but the keypress event is never fired for Escape. So you can only use keydown and keyup.
document.addEventListener('keypress', function(e) {
console.log('keypress fired; ', e.key);
})
document.addEventListener('keyup', function(e) {
console.log('keyup fired; ', e.key);
if(e.keyCode == '27') alert('Escape');
})

JS/JQuery on keypress proper usage

I'm working on creating a more accessible navigation, and in particular want to use determine whether a keypress is used. While I want to figure out why this is not working for me, I also want to know the difference between several methods that do the same thing. Those methods are:
$('ul li a').on('keypress', function(e){...});
& $('ul li a').keypress(function(e) {...});
& $('ul li a').bind('keypress', function(e) {...});
What is the difference if any? And is there a 'right' one to use for this siutation? Either way, none of them are actually working for me. I have setup console logs throughout the script I have written and while the console is logging the script loading, it detects the keydown, however it does not detect the return key being pressed, the whole script looks like:
$('ul li a').on('keypress', function(e){
if(e.keyCode==13){ // return / enter key
console.log("Return Key Pressed");
}
return false;
});
Thanks!
** EDIT **
I never discovered why the return key (or down arrow) was not working, neither would trigger the keydown event in the console, but I did discover the spacebar is the best method for accessibility, the end result looked like:
$('ul li a').on('keypress', function(e){
if ((e.keyCode || e.which) == 32) { // spacebar
... script ...
return false;
}
});
Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.
However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.
If you look in the source code for $.fn.bind you will find that it's just an rewrite function for on:
function (types, data, fn) {
return this.on(types, null, data, fn);
}
For keypress function, i don't recommend it because it work only for exsiting elements ; if element will be exist after running keypress , it will not handle new elements.
Instead you can use delegate :
$(document).delegate('ul li a','keypress',function(event){
//........
})
.on() is the preferred way to do all events in jQuery 1.7+
As of jQuery 1.7, the .on() method provides all functionality required
for attaching event handlers.
From the official docs: http://api.jquery.com/on/
Other methods of attaching events appear to be deprecated:
For help in converting from older jQuery event methods, see .bind(),
.delegate(), and .live().

iOS 9 - keyup event not firing

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.

Enabling keyboard listener (ctrl+Z) on specific DOM element

I am trying to bind the keyboard event ctrl+z through jquery only when a backbone view is rendered and when view is removed, I am unbinding it. But the problem is I want to unbind only the ctrl+z event only for current view.
on Initializing view:
$(document).keydown(function(e){
if((e.which === 90 && e.ctrlKey && e.shiftKey) || (e.which === 89 && e.ctrlKey)){
console.log('control + shift + z || control + y');
//redoAction;
}
else if(e.which === 90 && e.ctrlKey){
console.log('control + z');
//undoAction;
}
});
On removing view:
$(document).off('keydown');
But the last statement will unbind all the keyboard listeners. I don't want that.
Give a name to your handler function in a declaration (or by assigning it to a variable). Then you can use that name to refer the handler within .off():
// Create a named function
function handler (e) {
if((e.which === 90 ...)
}
// Attach event
$(document).on('keydown', handler);
//Detach event
$(document).off('keydown', handler);
Try using "on" handler with a selector and then you can use same selector to unwire events with 'off'. Following is a basic example though not exactly in your problem space, but the concept should be useful to you too.
<p id="pOne">Click this paragraph to change its background color.</p>
<button id="btn1">Remove the click event with off()</button>
<script>
$(document).ready(function(){
$(document).on("click","#pOne",function(){ //Notice use of "on" here
$(this).css("background-color", "pink");
});
$("#btn1").click(function(){
$(document).off('click','#pOne');
//Notice here same selector: #pOne, used with "on"
});
});
</script>
To check the specific event, you can use handler function as last argument similar to other jQuery events.
More from jQuery 'Off' documentation
Hope this may help you.
You can take advantage of jQuery's event namespacing feature:
// Add multiple listeners under the 'foo' namespace.
$(document).on('keydown.foo', handler1);
$(document).on('keyup.foo', handler2);
// Unbind all listeners at once without keeping reference to the various handlers.
$(document).off('.foo');
This is a actually a pattern used by Backbone's View class to easily remove all handlers that are added by the framework to the view's DOM element.

How to trigger click on keypress with jquery

I need to trigger click on some keypress action, also if it's a up or down key on my keybord script will be removing some class from specify element. So keypress is working but trigger and up down press not, this is my code, ths for help.
$('.main_search_field').keypress(function(evt){
$('.live_search_plugin').addClass('visible');
var scroll_pane = $('.scroll-pane');
scroll_pane.click();
scroll_pane.trigger('click');
if (evt.keyCode == 40) {
$('.live_search_list ul li').removeClass('active');
}
});
You can try following code:
var e = jQuery.Event("keypress");
e.which = 50;
$(".main_search_field").trigger(e);
In e.which put code for required character.
You have to check for the evt keypress like so:
if (evt.which == 40) { }
When using keypress, usually I check for which key I want to interact with before running any code inside my function. If you don't do this, your code will run with any keypress.
.keypress() might not be your best solution here, you could be better off using keydown() and keyup(), or to use the full version: .bind('keydown', handler) (ditto for keyup)
From the jquery docs:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
http://api.jquery.com/keypress/
.click() is shorthand for .trigger("click") and you are using it fine, but do you actually have a click handler on $('.scroll-pane)?
Your code will (assuming browser dependencies) cause two clicks to be triggerred on $('.scroll-pane') and then the if() to be evaluated. But you haven't shown us your click handler for scroll-pane so we can't see if that's at fault.

Categories

Resources