1

I am using the keyup event of jQuery. It is working fine with all keys except F5. Here is the code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(document).keyup(function(e){
    alert(e.keyCode); // This is not working always when we press F5
  });
});
</script>
</head>
</html>

I am getting alert on pressing all keys but it is not working fine with F5. Sometimes alert is fired with F5 and sometimes not. I have tried this on Chrome as well as Firefox.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vardan
  • 454
  • 1
  • 5
  • 18

2 Answers2

8

Pressing F5 reloads the page.

It seems like the page reload is initiated on the keydown or keypress event, so your alert fires too late. Depending on how long you press the key, the mouseup event is still triggered, and the alert shows briefly, but it doesn't block the reloading process.

If you bind the handler to the keydown event as well, page reload is only performed after the the alert is dismissed.

DEMO (click in the empty HTML area first, too ensure it's focused)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

If you capture the 'keypress' event, you also block the 't' key. For some reason both the keycode and ASCII keycode are both captured if you use the 'keypress' event (which you can't see in the chrome debugger). The F5 key is '116', but the ASCII keycode for 't' is also 116, so with the 'keypress' event you block F5, but you also block 't' app-wide.

so,Try this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){


 $(document).bind('keyup', function(e) {
    alert(e.keyCode);  

  });   
 $(document).bind('keypress', function(event) {
    if (event.keyCode == 116){
     alert("f5"); 
    }    

  });  
});
</script>
Mr7-itsurdeveloper
  • 1,631
  • 2
  • 17
  • 24