Isaiah Bugarin
Isaiah Bugarin

Reputation: 493

Key input not working Chrome?

I have some code to run a function on a key press:

document.onkeypress=function(e)
{
         var e=window.event || e
         var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
         var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
    if (unicode == 39)
    {
         Rotate();
    }
}

    function Rotate()
    {
        myDiv.setAttribute('style', '-moz-transform:rotate(' + rotationAmount + 'deg); -o-transform:rotate(' + rotationAmount + 'deg);-webkit-transform:rotate(' + rotationAmount + 'deg);-ms-transform:rotate(' + rotationAmount + 'deg)');
    }

And for whatever reason, the key input works in Firefox, but not Chrome. When I press a key in Chrome, nothing happens. I know that the Rotate() function is working in Chrome because if I call it under different conditions, it runs with no problem.

Upvotes: 0

Views: 730

Answers (1)

Tim Down
Tim Down

Reputation: 324527

You seem to be detecting the right arrow key. For this and any other non-printable keystroke you should use the keydown event instead and just use the keyCode property, which works in all major browsers. You can also simplify your event code:

document.onkeydown = function(e)
{
    e = e || window.event;
    if (e.keyCode == 39)
    {
         Rotate();
    }
};

Upvotes: 1

Related Questions