Solved

Does javascript provide any way of specifying the keycode without writing the number

Posted on 2016-11-06
2
69 Views
Last Modified: 2016-11-15
HI,
Currently in my javascript code inside keydown evenListener i am using code :
e.keyCode == 38
38 is for up button.. Is there a better way to write the same by getting rid of 38 magic number something inbuilt in javascript ?

Thanks
0
Comment
Question by:Rohit Bajaj
2 Comments
 
LVL 9

Assisted Solution

by:Paweł
Paweł earned 200 total points
ID: 41876096
in short no

you can use this site to figure them out

http://keycode.info/

if you really want you could create a javascript object that could store them, sort of like an enum in c# with friendly names
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 300 total points
ID: 41876205
@Pawel is right, nothing inbuilt in javascript
Example of object below :
Test page : https://jsfiddle.net/86hnL05s/

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

document.onkeydown = function(e) {
    switch(e.keyCode) {
        case KEY.UP: write("you pressed up key");break;
        case KEY.DOWN: write("you pressed down key");break;
        default: break;
   }
}

var write = function(what) {
   document.getElementsByTagName("div")[0].innerHTML = what;
}

Open in new window

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question