Link to home
Start Free TrialLog in
Avatar of drhamel69
drhamel69

asked on

Onkeydown wont fire properly in Firefox or Google Chrome.

I have a web application where my custer wants to use the plus sign on the number pad as a tab.  The following code below works with Internet Explorer but now with any other browsers and I can't figure out why?



<script type="text/javascript" language="javascript">
    function convertEnterToTab() {
      if(event.keyCode==107) {
        event.keyCode = 9;
      }
    }
    document.onkeydown = convertEnterToTab;    
  </script>

Open in new window

Avatar of sjklein42
sjklein42
Flag of United States of America image

Try adding "event" as an argument to convertEnterToTab:

<script type="text/javascript" language="javascript">
    function convertEnterToTab(event) {
      if(event.keyCode==107) {
        event.keyCode = 9;
      }
    }
    document.onkeydown = convertEnterToTab;    
  </script>

Open in new window

Avatar of drhamel69
drhamel69

ASKER

Nope.  Didn't work sjklein42
Based on what I've learned, the way you pick up the event is different in IE and Firefox.  Also whether the event is writable or readonly.

In Firefox, you must pick up the event as an argument.  Not so in IE.

In Firefox, the event is read-only, so you must create and dispatch a new event based on the old one, and then cancel the old event before it gets executed.

I found a couple examples and came up with this code, which "should" work but doesn't.  For some reason, even though the new event is being dispatched, it is not having any effect.

(By the way, if you are not already using the Firebug add-on to Firefox, I strongly recommend you install it right away.)

<script type="text/javascript" language="javascript">

function convertEnterToTab(winEvent) {
	var keyCode;     // event passed as param in Firefox, not IE where it's defined as window.event
	if(!winEvent) {
		winEvent = window.event;
		keyCode = winEvent.keyCode;
		if(keyCode==107) {
			winEvent.keyCode= 9;
		}
	}
	else {			 // ff
		keyCode = winEvent.which;
		if(keyCode==107) {
			var newEvent = document.createEvent("KeyboardEvent")
			newEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, 9, 0)
			winEvent.preventDefault()
			winEvent.target.dispatchEvent(newEvent)
		}
	}
}

document.onkeydown = convertEnterToTab;    

</script>

Open in new window

I kept trying, and then found this.  The plot thickens:

http://forums.mozillazine.org/viewtopic.php?f=19&t=665240

(no solution posted)

ASKER CERTIFIED SOLUTION
Avatar of sjklein42
sjklein42
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial