catching shift+ keypresses

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
newmember
Forum Contributor
Posts: 252
Joined: Fri Apr 02, 2004 12:36 pm

catching shift+ keypresses

Post by newmember »

Hi

Is it possible to catch "SHIFT+some digit" keypresses?

(for example if i press SHIFT+4 i want to get $ as a result and not '4' and 'shiftKey=true')
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

On a UK keyboard at least, shift and 4 would print a dollar sign in any textarea etc...

Are you talking about capturing ascii codes keyed by the user?

Find an ascii table (google for it... ) then see what SHIFT+4 is numerically and use something like...

Code: Select all

function isAsciiCode(x)
{
	
	e = window.event;
	if( e.keyCode == x ) return true;
}

//bla bla.. some html
<input type="text" onkeypress="isAsciiCode(09)" ....>
User avatar
newmember
Forum Contributor
Posts: 252
Joined: Fri Apr 02, 2004 12:36 pm

Post by newmember »

i'm using regular english layot keyboard...
i set up both onkeydown and onkeypress events to trigger and i'm testing with firefox and ie....

Code: Select all

document.onkeydown=printKeyOnKeyDown;
document.onkeypress=printKeyOnKeyPress;
each event handler has these lines:

Code: Select all

function printKeyOnKeyDown(e)
{
var ev=!e ? window.Event : e;
var code=!e ? ev.keyCode : ev.which;
var str=String.fromCharCode(code);
alert('[ONKETDOWN] code='+code+'  char='+str);
}
when i press,say SHIFT+5, according to what i read the following should happen...
- onkeydown handler should be triggered twice... for shift key and then for the actual key...(so i have the chance to cancel the default action for modifier key)
- onkeypress handler triggered only once... it will recieve actual key and the modifier key at single call...

but i have very different results...
the instance i touch the shift key both handlers(onkeypress first and onkeydown after it) are called and they print 16 for keycode(that i guess the code for shift key) and nothing more... :?
so for example if i press SHIFT+3 , the 3 is kind of lost, both handlers print only 16 as keycode...
What i'm doing wrong?

and another odd issue...
let's say i pressed 'k'(small 'k'), then onkeydown return correct code for letter 'k' and prints 'k'
but onkeypress returns key code for letter 'K' and prints capital 'K'... :?
Why is that?
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

use this whereever you need in body or input tags

Code: Select all

onkeypress="if(event.shiftKey){alert(event.keyCode)};"
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

long winded (pretty) working example:

Code: Select all

<html>
	<head>
		<title>key down, key press and key up fun</title>
		<script language="Javascript">
			function handleEvent()
			{
				var type = null;
				var code = null;
				var state = '';
				if(arguments.length)
				{
					var e = arguments[0];
					/*
					var buf = new Array();

					for(var i in e)
					{
						buf[buf.length] = 'event[' + i + '] = ' + e[i];
					}
					debugPre.innerHTML += buf.join('\n') + '-------------------------------\n\n';
					*/

					type = arguments[0].type;
					code = arguments[0].which;

					if(e.ctrlKey)
						state += (state.length ? '+ ' : '') + 'Ctrl';
					if(e.shiftKey)
						state += (state.length ? '+ ' : '') + 'Shift';
					if(e.altKey)
						state += (state.length ? '+ ' : '') + 'Alt';
					if(e.metaKey)
						state += (state.length ? '+ ' : '') + 'Meta';

					state += (state.length ? '+' : '');
				}
				else
				{
					var e = window.event;
					/*
					var buf = new Array();
					for(var i in e)
					{
						buf[buf.length] = 'event[' + i + '] = ' + e[i];
					}
					debugPre.innerHTML += buf.join('<br />\n') + '<br />\n-------------------------------<br />\n<br />\n';
					*/

					type = e.type;
					code = e.keyCode;

					if(e.ctrlKey)
						state += (state.length ? '+ ' : '') + 'Ctrl';
					if(e.shiftKey)
						state += (state.length ? '+ ' : '') + 'Shift';
					if(e.altKey)
						state += (state.length ? '+ ' : '') + 'Alt';

					state += (state.length ? '+' : '');
				}
				var obj = document.createElement('DIV');
				obj.className = (toggle ? 'odd' : 'even');
				obj.innerHTML = '[' + type + '] ' + state + String.fromCharCode(code) + ' (' + code + ')';
				var elem = (document.getElementById ? document.getElementById('log') : document.all['log']);
				elem.appendChild(obj).scrollIntoView(false);
				var sc = (document.getElementById ? document.getElementById('footer') : document.all['footer']);
				sc.scrollIntoView(false);
				toggle = (toggle + 1) % 2;
			}

			var toggle = 0;

			document.onkeypress = handleEvent;
			document.onkeydown = handleEvent;
			document.onkeyup = handleEvent;
		</script>
		<style>
			html
			{
				font-family: 	Georgia, Tahoma, Verdana, Arial, Helvetica, sans-serif;
				font-size: 	12pt;
				margin:		0;
				padding:	0;
			}

			body
			{
				margin:		5px;
				padding:	0;
			}

			.container
			{
				position: 	relative;
				left: 		3px;
				top: 		3px;
				width:		auto;
				height:		auto;
				display:	inline;	/* for flow-around */
			}

			.box
			{
				position: 	relative;
				left: 		-3px;
				top: 		-3px;
				z-index:	5;
				background:	white;
				border: 	1px solid gray;
				width:		auto;
				height:		auto;

				/* beautify */
				padding:	2px 4px;
			}

			.shadow
			{
				position:	relative;
				left: 		auto;
				top:		auto;
				z-index:	1;
				background:	silver;
				border: 	1px solid gray;
				width:		auto;
				height: 	auto;

				/* beautify */
				margin-top: 13px;
				margin-bottom: 10px;
			}

			.odd
			{
				background-color:	#EEF;
			}

			.even
			{
				background-color:	whitesmoke;
			}

			#footer
			{
				clear: both;
			}
		</style>
	</head>
	<body>
		Press some keys!
		<div class="container"><div class="shadow"><div id="log" class="box"></div></div>
		<div id="footer"></div>
		<pre id="debugPre"></pre>
	</body>
</html>

[edit] Updated it a bit to add automatic scrolling to the last key entry
Last edited by feyd on Thu Aug 18, 2005 11:48 am, edited 1 time in total.
User avatar
newmember
Forum Contributor
Posts: 252
Joined: Fri Apr 02, 2004 12:36 pm

Post by newmember »

ok...the problem SOLVED by itself.. after i removed calles to alert() ... :)
i recall that i read somewhere that alert() inside event handlers can disturb the normal event flow....
probably that is what happened in my case... :?

feyd, thanks for example...

but i still don't understand why when i press 't' (lowercase letter) onkeydown returns keycode of 'T'(capital letter)
and onkeypress returns keycode of 't'(lowercase)?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'd guess that because capital 't' is the first character to hit when iterating over the character that matches the virtual key code. KeyPress is after processing from the browser/OS, so it's been translated to an actual character, while keyDown/keyUp is a VK_ code.. at least that's how keyboard messages work in the Windows message pump.
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

This easily prints out the character you pressed.

Code: Select all

onkeypress="if(event.shiftKey){alert(String.fromCharCode(event.keyCode))}else{alert(String.fromCharCode(event.keyCode))};"
ex: this would display 'k' when u press 'k' and displays 'K' when you press it.

Forgive me if I still get your q wrong.
Post Reply