Javascript: window.location.href inside a & ldquo; If & rdquo;

advertisements

I am a total newby in javascript and I am stuck with a problem.

Everything is happening within this "body" :

<body onKeyDown="myFunction(event);">

This code works : when I press escape on the page, there is a popup with 27. When I press another key, nothing happens. This is what I wanted.

Key_ESC = 27;
function myFunction(event) {
    if ( event.keyCode == 27 ){
        alert(event.keyCode);
    }
}

This code works : When I press any key, I go to next page. This is what I wanted.

Key_ESC = 27;
function myFunction(event) {
        window.location.href=\"$INDEX/image`expr $compteur + 1`.html\";
}

But this one doesn't work : when I press any key nothing happens. I thought pressing escape would make a change of page (just like without the "if". It is not the case.

Key_ESC = 27;
function myFunction(event) {
    if ( event.keyCode == 27 ){
        window.location.href=\"$INDEX/image`expr $compteur + 1`.html\";
    }
}

Could any one explain to me why "window.location" doesn't work inside a "if" ? What did I do wrong ? I really have no idea at all....

Thank you very much.


You probably have to call event.preventDefault

also, in JS just do:

window.onload = function ()
{

Key_ESC=27;
Key_LEFT=37;

document
.   event =
    {   preventDefault: function( e )
        {   e.preventDefault?e.preventDefault():e.returnValue=false;
        }
    }
;
document.body
.   onkeyup = function nextPage ( e )
    {
        switch
        (   e.keyCode
        )   {   case Key_ESC
                :   document.event.preventDefault(e);
                    window.location.href=URL_NEXT;
                case Key_LEFT
                :   document.event.preventDefault(e);
                    window.location.href=URL_PREV;
            }
    }

}