4058d6b5dc2bfd92fd7f7f9a13eb61a6

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.

<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 !

0135bb75b1f08484d26239e8117b111c

Jacob Relkin

August 19, 2010, August 19, 2010 16:29, permalink

2 ratings. Login to rate!
<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>
4058d6b5dc2bfd92fd7f7f9a13eb61a6

Anri

August 19, 2010, August 19, 2010 16:55, permalink

No rating. Login to rate!

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?

D41d8cd98f00b204e9800998ecf8427e

lomax

September 15, 2010, September 15, 2010 19:18, permalink

No rating. Login to rate!

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;
  }
}

Your refactoring





Format Copy from initial code

or Cancel