2

I noticed that jquery has a keypress function. But it seems that it can only detect keypress event of numbers and characters. It cannot detect the F5 keypress event. And What surprises me the most is everyone online says that the keyCode of F5 is 116, But when I use the jquery keypress function, it just shows that the character t has the keyCode of 116(it seems that 116 is the ascii code of lowercase t)! Can somebody give me any idea about this and how to detect the F5 event in javascript or jquery? Thanks so much in advance.

chaonextdoor
  • 5,019
  • 15
  • 44
  • 61

3 Answers3

5

I don't know what you did wrong in your code, but jQuery does say F5 is 116 and t is 84:

http://jsfiddle.net/Brjb2/1

One possible error is keypress will have different keycode, that's why keydown is more preferred.

        |  T  |  A  |  F5
keydown |  86 |  65 | 116
keypress| 116 |  97 |  -

Also pressing F5 will not trigger keypress because the reload part happens before keypress.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
4

The keypress event does not accept function keys(F1-F12). You can try to use keydown event.

Ricky Jiao
  • 531
  • 4
  • 10
  • 1
    Exactly right. More specifically "keypress" refers to the event where something is typed. If the button you press would cause something to happen in a textarea, then the `keypress` event fires. `keydown`, however, fires for all keys. – Niet the Dark Absol Dec 14 '12 at 05:07
  • The 'keypress' will be fired repeat if you hold one normal key, however the 'keydown' will be fired only one time for each keystroke. – Ricky Jiao Dec 14 '12 at 05:12
  • That's for the same reason as it firing in the first place. Its frequency depends on the keyboard settings. – Niet the Dark Absol Dec 14 '12 at 05:13
  • Yes. This topic can refer JS Event model/order at here http://www.quirksmode.org/js/events_order.html. – Ricky Jiao Dec 14 '12 at 05:16
1

this code works good for me
i tested it in chrome and firefox successfully

<script>
    document.onkeydown = capturekey;
    document.onkeypress = capturekey;
    document.onkeyup = capturekey;

    function capturekey(e) {
        e = e || window.event;
        //debugger
        if (e.code == 'F5') {
            if (confirm('do u wanna to refresh??')) {
                //allow to refresh
            } 
            else {
                //avoid from refresh
                e.preventDefault()
                e.stopPropagation()
            }
        }
    }
</script>
R.Akhlaghi
  • 729
  • 1
  • 12
  • 23