What is keycode in javascript

KeyCode vs. .which

It keeps all the JavaScript code together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers. So I’ve seen some forums posts about different browsers reporting differenct keyCodes, but everyone seems so avoid the «why?».

KeyCode vs. .which

I thought this would be answered somewhere on Stack Overflow, but I can’t find it.

If I’m listening for a keypress event, should I be using .keyCode or .which to determine if the Enter key was pressed?

I’ve always done something like the following:

But I’m seeing examples that use .which instead of .keyCode . What’s the difference? Is one more cross-browser friendly than the other?

Note: The answer below was written in 2010. Here many years later, both keyCode and which are deprecated in favor of key (for the logical key) and code (for the physical placement of the key). But note that IE doesn’t support code , and its support for key is based on an older version of the spec so isn’t quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn’t support code either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.

Читайте также:  Javascript get all matches

Some browsers use keyCode , others use which .

If you’re using jQuery, you can reliably use which as jQuery standardizes things; More here.

If you’re not using jQuery, you can do this:

var key = 'which' in e ? e.which : e.keyCode; 
var key = e.which || e.keyCode || 0; 

. which handles the possibility that e.which might be 0 (by restoring that 0 at the end, using JavaScript’s curiously-powerful || operator).

jQuery normalises event.which depending on whether event.which , event.keyCode or event.charCode is supported by the browser:

// Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) )

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined )

If you are staying in vanilla Javascript, please note keyCode is now deprecated and will be dropped:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any tim

Instead use either: .key or .code depending on what behavior you want: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Both are implemented on modern browsers.

I’d recommend event.key currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

event.KeyCode and event.which both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

For alphanumeric keys, event.key appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).

For alphanumeric keys a check would look something like:

For control characters you’d need to do something like:

event.key === 'Esc' || event.key === 'Escape' 

I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

event.code is mentioned in a different answer as a possibility, but IE10/11/Edge don’t implement it, so it’s out if you want IE support.

Javascript — keycode and charcode, Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for …

Javascript: different keyCodes on different browsers?

So I’ve seen some forums posts about different browsers reporting differenct keyCodes, but everyone seems so avoid the «why?».

I was trying to capture the colon (:) keyCode and realized that Firefox reports back e.keyCode 56. While Chrome reports back 186 (I think that’s what it was).

Is there a univeral way of getting the right keyCode across all browsers?

And why are they different if they are the same keys?

I would be more curious as to whether there is a international way of getting the same key press.

It depends whether you’re interested in which physical key the user has pressed or which character the user has typed. If it’s the character you’re after, you can get that reliably in all major browsers (using the keypress event’s which property in most browsers or keyCode in IE

An excellent explanation of and reference for all JavaScript key-related events can be found at http://unixpapa.com/js/key.html.

To detect the user typing a colon character reliably in all the major browsers, you could do the following:

document.onkeypress = function(e) < e = e || window.event; var charCode = (typeof e.which == "number") ? e.which : e.keyCode; if (charCode && String.fromCharCode(charCode) == ":") < alert("Colon!"); >>; 

See http://unixpapa.com/js/key.html for an explanation why they have different keys. I do not know of an international way to match keys.

This is an old question. The modern way to do this is use event.key. See MDN Key

I think you should make JavaScript to get the keycode of the ‘:’ character, so the script will know what is it in a certain environment. Similar question had been asked here, in stackoverflow.

Difference between != and !== operator in JavaScript, The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns true where strict equality would return false and vice versa. Strict inequality will not convert data types. For example 1 !== ‘1’ will return true since 1 is an integer and ‘1’ is a character and

Keypress and keyup — why is the keyCode different?

Here is some code you can try at home or in a jsfiddle:

el.addEventListener( 'keyup', function( e ) < console.log( 'Keyup event' ); console.log( e.keyCode ); >); el.addEventListener( 'keypress', function( e ) < console.log( 'Keypress event' ); console.log( e.keyCode ); >); 

Why is the keyCode different?

I can understand why one should use keypress only, but what I don’t understand is how two key events, given the same hit key on the keyboard, give different keyCodes.

PS: I’m not worrying about legacy browsers support, I tried this in Chrome and was surprised, and couldn’t find an explanation.

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don’t try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn’t be used (except in older IE, but see the linked document below for more on that); for printable keypresses it’s usually the same as which and charCode , although there is some variation between browsers.

Jan Wolter’s article on key events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.

There is a good article on quirksmode.org answering exactly that question. You might also want to look at Unixpapa’s results.

Well, I stumbled upon one difference when i was trying to copy user’s entry from one input of the form to some other part of the form , which I had locked for my for users to edit. What i found was, that whenever a user moved to the next label using key upon completing the input, one last keyboard entry was missed in the copied entry when I used eventListener to keypress and this got resolved on using keyup.

So, in conclusion Keypress listens to the state at the instant when the key was pressed, leaving aside the result of keypress , whereas keyup listens to the system status after the key has been pressed and includes the result of the keypress.

Python VS JavaScript – What are the Key Differences, 💡 Tip: To run and test small code snippets of JavaScript code, you can use the console in Chrome Developer Tools. Data Types and Values in Python and JavaScript. Let’s see the main differences between Python and JavaScript data types. Numeric Data Types. Python has three numeric types to help us …

What is the difference between the different methods of putting JavaScript code in an <a>?

I have seen the following methods of putting JavaScript code in an tag:

I understand the idea of trying to put a valid URL instead of just JavaScript code, just in case the user doesn’t have JavaScript enabled. But for the purpose of this discussion, I need to assume JavaScript is enabled (they can’t login without it).

I personally like option 2 as it allows you to see what’s going to be run–especially useful when debuging where there are parameters being passed to the function. I have used it quite a bit and haven’t found browser issues.

I have read that people recommend 4, because it gives the user a real link to follow, but really, # isn’t «real». It will go absolutely no where.

Is there one that isn’t support or is really bad, when you know the user has JavaScript enabled?

Related question: Href for JavaScript links: “#” or “javascript:void(0)”? .

I quite enjoy Matt Kruse’s Javascript Best Practices article. In it, he states that using the href section to execute JavaScript code is a bad idea. Even though you have stated that your users must have JavaScript enabled, there’s no reason you can’t have a simple HTML page that all your JavaScript links can point to for their href section in the event that someone happens to turn off JavaScript after logging in. I would highly encourage you to still allow this fallback mechanism. Something like this will adhere to «best practices» and accomplish your goal:

Why would you do this when you can use addEventListener / attachEvent ? If there is no href -equivalent, don’t use an , use a and style it accordingly.

You forgot another method:

5: With the JavaScript code:
document.getElementById('myLink').onclick = function() < // Do stuff. >; 

I can’t comment on which of the options has the best support or which is semantically the best, but I’ll just say that I much prefer this style because it separates your content from your JavaScript code. It keeps all the JavaScript code together, which is much easier to maintain (especially if you are applying this to many links), and you can even put it in an external file which can then be packed to reduce filesize and cached by client browsers.

Depending on the situation. For larger apps, the second one is best because then it consolidates your event code.

JavaScript Object.keys( ) Function, An Object in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object. Constructors are general JavaScript …

Источник

Оцените статью