onKeyUp not firing for ESC in IE

I have a page where I have to close a dialog when Esc is pressed. I wrote the following simplified code example for this task:

<html>
<head>
<script language="JavaScript">
function keyUpExample() {
alert('on' + event.type + ' event fired by ' + '"' + event.srcElement.id + '" ' + ' ' +        event.which) 
} 
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
    Trying keyUp event: Press any key...
</body>
</html>

This works as expected under Chrome but is NOT working under IE 7. Is there any workaround on order to cope this problem?

Thanks in advance!

Answers:

Answer

Key events don't have to be caught by the body, but document or window works across browsers. Also, keyCode returns the correct value for keyup or down events.

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<html>
<head>
<script>
function keyUpExample(e){
    e=e || window.event;
    var  who= e.target || e.srcElement;
    alert(e.type+' caught at '+who.nodeName+ ': key #'+e.keyCode) 
}
window.onload=function(){
    document.onkeyup= keyUpExample; 
    document.body.onkeyup= keyUpExample;    
}
</script>
</head>
<body>
    Trying keyUp event: Press any key...
</body>
</html>
Answer

Pass event as an argument to the callback, and check for window.event for IE.

<html>
<head>
<script>
function keyUpExample(e) {
    e = e || window.event;
    alert('on' + e.type + ' event fired by ' + '"' + e.srcElement.id + '" ' + ' ' +        e.which) 
} 
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
    Trying keyUp event: Press any key...
</body>
</html>

Demo

element.onkeyup reference

However

You're better off using a library which smooths out all the ugly cross-browser inconsistencies. Take your pick: jQuery, Prototype, YUI, Dojo, MooTools, RightJS...

Answer

Are you allowed to use jQuery? If so, then you can accomplish it with .keyup().

Using jQuery also means you can generally leave the cross-browser worries to somebody else.

Answer

try

function keyUpExample(e) {
  var evt = e || event;
  alert('on' + evt.type + ' event fired by ' + '"' + ((evt.srcElement)?evt.srcElement.id:evt.target.id) + '" ' + ' ' +        ((evt.which)?evt.which:evt.keyCode)) 
} 
Answer

It is actually very simple, a raw JavaScript solution could look kinda like this

function callback(event) {
  if (event.keyCode == 27) {
    alert('Here you go!');
  }
}

if (document.addEventListener) {
  document.addEventListener('keydown', callback, false);
} else {
  document.attachEvent('onkeydown', callback);
}

Just attach it to the document no need for any onload trickery.

Also, as people suggested you, check RightJS, it's very lightweight and friendly, and you will be able to do things like those :)

http://rightjs.org/plugins/keys

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.