<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e){
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID){
KeyID.preventDefault();
case 33:
case 37:
alert('You are already on the First Page.');
break;
case 34:
case 39:
alert('This is the latest page.');
break;
}
}
</script>
Refactorings
No refactoring yet !
Jacob Relkin
August 19, 2010, August 19, 2010 16:29, permalink
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e){
var ev = e || window.event;
ev.preventDefault();
var KeyID = ev.keyCode;
switch(KeyID){
case 33:
case 37:
alert('You are already on the First Page.');
break;
case 34:
case 39:
alert('This is the latest page.');
break;
}
}
</script>
Anri
August 19, 2010, August 19, 2010 16:55, permalink
Hey Jacboc, I tested this in Chome. But it seems to be... doing nothing. What browser have you tested this in? Also, if I wanted to restrict the "preventDefault" function to the key that are being press, would I just stick it in the switch?
lomax
September 15, 2010, September 15, 2010 19:18, permalink
It's "doing nothing" because you're canceling the default behavior of keyup, not keydown or keypress. Additionally, some keys can't be canceled in some browsers, due to security/user confusion concerns. You'll also want to add "ev.returnValue=false;" if you care about IE.
The answer to your second question is "yes."; if you want to cancel the event conditionally, place the cancel statement inside your condition.
I would make a more generic function, and simply call it to cancel your event, though:
function cancelEvent(e){
if(!e)return;
if(e.preventDefault)e.preventDefault();
return e.returnValue=false;
}
function KeyCheck(e){
if(!e)e=window.event;
switch(e.keyCode){
case 33:
case 37:
cancelEvent(e);
alert('You are already on the First Page.');
break;
case 34:
case 39:
cancelEvent(e);
alert('This is the latest page.');
break;
}
}
I am attempting to add Prevent Default to the event when the keys are press, but to no avail, I am not getting anywhere. Can someone give me a little help here. Thank you and much appreciated.