Solved

onKeyPress event.keyCode Firefox

Posted on 2006-07-21
11
123,232 Views
Last Modified: 2012-06-21
I saw a few questions that didn't really make any sense to me so I'm hoping that there's a really simple solution to my problem here.

I have this code.

onKeyPress="if (event.keyCode==45) event.returnValue=false;"

it works in IE but not in Firefox.

I tried putting the returnValue part in {} that didn't help me either. Sorry if this is really simple, and if it was answered elsewhere but like i said, the answers didn't make any sense to me. Thanks ahead of time if anyone can help me.
0
Comment
Question by:arvanhalleorg
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +2
11 Comments
 
LVL 2

Author Comment

by:arvanhalleorg
ID: 17158241
Oh and I tried doing a onKeyPress="alert(event.keyCode);" no matter what key i hit when i'm in Firefox, it will show 0 as the value. Any ideas?
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 17158251
IN FireFox it is not keyCode, it is "which":  http://www.quirksmode.org/js/events_properties.html

0
 
LVL 12

Expert Comment

by:netsmithcentral
ID: 17158348
"which" is a Netscape property.  Try registering the event handler as an anonymous function rather than a string variable.  Also, returnValue is a difficult property to work with.  It's likely the script ultimately won't be fully cross browser if you use it that way.

onkeypress = function (e) {
  if(!e) e=window.event;
  key = e.keycode ? e.keycode : e.which;
  if(key==45) e.returnValue=false;
}


NOTE: For browser event compatibility info go here: http://www.quirksmode.org/dom/w3c_events.html
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Author Comment

by:arvanhalleorg
ID: 17158403
Uhm. I'm having a little trouble understanding that.

How would I add that to my onKeyPress? Is it in the event with the object that the event belongs with? or is that a function defined elsewhere that i have to do like... onKeyPress="function(window.event.keyCode);" ?
0
 
LVL 5

Expert Comment

by:maclema
ID: 17162339
Try This:

Put the following code in a .js file and include it in your html page:
var Keys = {
      BACKSPACE: 8,            TAB: 9,                  ENTER: 13,            SHIFT: 16,
      CTRL: 17,                  ALT: 18,            PAUSE: 19,            CAPS: 20,
      ESC: 27,                   PAGEUP: 33,       PAGEDN: 34,       END: 35,
      HOME: 36,                  LEFT: 37,             UP: 38,             RIGHT: 39,
      DOWN: 40,                  INSERT: 45,       DELETE: 46,       
      n0: 48,      n1: 49, n2: 50, n3: 51, n4: 52,
      n5: 53, n6: 54,      n7: 55,      n8: 56,      n9: 57,
      A:65, B:66, C:67, D:68, E:68, F:70, G:71, H:72, I:73, J:74, K:75,
      L:76, M:77, N:78, O:79, P:80, Q:81, R:82, S:83, T:84, U:85, V:86,
      W:87, X:88, Y:89, Z:90,
      WINLEFT: 91,             WINRIGHT: 92,      SELECT: 93,       NUM0: 96,
      NUM1: 97,                   NUM2: 98,             NUM3: 99,             NUM4: 100,
      NUM5: 101,                   NUM6: 102,             NUM7: 103,             NUM8: 104,
      NUM9: 105,                   MULTIPLY: 106,       ADD: 107,             SUBTRACT: 109,
      DECIMAL: 110,             DIVIDE: 111,       F1: 112,             F2: 113,
      F3: 114,                   F4: 115,            F5: 116,             F6: 117,
      F7: 118,                   F8: 119,             F9: 120,             F10: 121,
      F11: 122,                   F12: 123,             NUMLOCK: 144,       SCROLLLOCK: 145,
      SEMICOLON: 186,       EQUAL: 187,       COMMA: 188,       DASH: 189,
      PERIOD: 190,             FORWARDSLASH: 191,                         GRAVEACCENT: 192,
      OPENBRACKET: 219,       BACKSLASH: 220,                              CLOSEBRACKET: 221,
      QUOTE: 222
};

function KeyPressEvent(eventObj)
{
      this.eventHandler = null;     //the event handler
      this.eventElement = null;     //the element that caused the event
      this.elementTag = "";         //the html tag that caused the event
      this.elementID = "";          //the id of the element
      this.element = null;          //the actual element
      this.keyCode = 0;             //the keycode to capture
      
      if( document.all )
      {
            // IE
            this.eventHandler = eventObj;
            this.eventElement = eventObj.srcElement;
            this.elementTag = eventObj.srcElement.tagName;
            this.elementID = eventObj.srcElement.name;
            this.element = eventObj.srcElement;
            this.keyCode = eventObj.keyCode;
      }
      else
      {
            // Not IE
            this.eventHandler = eventObj;
            this.eventElement = eventObj.target.srcElement;
            this.elementTag = eventObj.target.tagName;
            this.elementID = eventObj.target.name;
            this.element = eventObj.target;
            this.keyCode = eventObj.which;
            
            // Safari bug workaround
            if (this.element.nodeType == 3)
                  targ = targ.parentNode;
      }
}

function KeyHandler()
{
      //register for the event
      if ( document.addEventListener )
            document.addEventListener("keydown", this.keyDown.bind(this), false);
      else if ( document.attachEvent )
            document.attachEvent("onkeydown", this.keyDown.bind(this));
      else
            document.onkeydown = this.keyDown.bind(this);
            
      if (document.layers) document.captureEvents(Event.KEYDOWN);
      
      if ( document.addEventListener )
            document.addEventListener("keyup", this.keyUp.bind(this), false);
      else if ( document.attachEvent )
            document.attachEvent("onkeyup", this.keyUp.bind(this));
      else
            document.onkeyup = this.keyUp.bind(this);
            
      if (document.layers) document.captureEvents(Event.KEYUP);
}

KeyHandler.prototype.keyDown = function(e)
{      
      if ( typeof(this.onKeyDown) != "undefined" )
      {
            if ( !e ) e = window.event;
            var r = this.onKeyDown( new KeyPressEvent(e) );
            
            if ( r == false )
            {
                  if ( window.event ) window.event.cancelBubble = true;
              if ( window.event ) window.event.returnValue = false;
                  if ( e.preventDefault ) e.preventDefault();
              return false;
            }
            else
            {
                  if ( window.event ) window.event.cancelBubble = false;
              if ( window.event ) window.event.returnValue = true;
                  return true;
            }
      }
      else
      {
            alert("No Key Press Event Handler Found!");
      }
};

KeyHandler.prototype.keyUp = function(e)
{      
      if ( typeof(this.onKeyUp) != "undefined" )
      {
            if ( !e ) e = window.event;
            var r = this.onKeyUp( new KeyPressEvent(e) );
            
            if ( r == false )
            {
                  if ( window.event ) window.event.cancelBubble = true;
              if ( window.event ) window.event.returnValue = false;
                  if ( e.preventDefault ) e.preventDefault();
                  if ( e.stopPropagation ) e.stopPropagation();
              return false;
            }
            else
            {
                  if ( window.event ) window.event.cancelBubble = false;
              if ( window.event ) window.event.returnValue = true;
                  return true;
            }
      }
      else
      {
            alert("No Key Press Event Handler Found!");
      }
};


Useage:

var kh = new KeyHandler();
kh.onKeyDown = function(e)  // e is a KeyPressEvent object
{
    if ( e.eventElement == document.getElementById("textbox1") && e.keyCode == 45 )
        return false; //cancel the press
 
    //more information available from e
    e.eventHandler     //the event handler
    e.eventElement      //the element that caused the event
    e.elementTag         //the html tag that caused the event
    e.elementID          //the id of the element
    e.element           //the actual element
    e.keyCode             //the keycode to capture

    return true;
}

kh.onKeyUp = function()
{
   //do nothing
   return true;
}

Hope that helps, Matt
0
 
LVL 5

Expert Comment

by:maclema
ID: 17162342
and if you lazy like me, rathe than looking up the keyCode you coud also do this

if ( e.keyCode == Keys.TAB )
0
 
LVL 2

Author Comment

by:arvanhalleorg
ID: 17163238
:/ uhm, wow, that's a whole ton of code for replacing a single line, that last thing looked quicker. is that assuming you've defined them in the .js file? or do the browsers actually understand the use of the words?
0
 
LVL 12

Accepted Solution

by:
netsmithcentral earned 500 total points
ID: 17164058
arvanhalleorg, to use my suggestion, put that code into a script tag in the head.  You would then register to it a specific element (eg, the document, or a textbox).


EXAMPLE

document.onkeypress = function () {
  if(!e) e=window.event;
  key = e.keycode ? e.keycode : e.which;
  if(key==45) e.returnValue=false;
}

OR

document.getElementById('atextbox').onkeypress = function () {
  if(!e) e=window.event;
  key = e.keycode ? e.keycode : e.which;
  if(key==45) e.returnValue=false;
}
0
 
LVL 5

Expert Comment

by:maclema
ID: 17166103
Yea, probally a little overdone, I was using that code for a full blown javascript app :S

netsmithcentral's suggesstion should work fine
0
 
LVL 2

Author Comment

by:arvanhalleorg
ID: 17185752
lol remind me not to try a full blown javascript app, i would die from a brain shortage.

that short one works :)
0
 

Expert Comment

by:hans_fast
ID: 25828971
NOTE: netsmithcentral's solutions has two typos:
- e must be passed as parameter
- e.keycode is misspelled.

Solution should read:

document.onkeypress = function (e) {
  if(!e) e=window.event;
  key = e.keyCode ? e.keyCode : e.which;
  if(key==45) e.returnValue=false;
}
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Debugging Html 8 31
ModalPopup  question 22 38
Link Anchor Not working 9 49
How do I split a variable to newline 2 16
This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
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…

749 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