How to Detect F5 Key in Javascript

In this tutorial, you will learn how to detect F5 key in javascript. In a standard keyboard layout, the first row contains in total 13 keys. These 13 keys are divided into 4 sections. The first section only contains the escape key.

The other 3 sections contain keys from F1 to F12. Each of these sections contains only 4 keys. The F5 key is located in the third section of the first row on the left. It is generally used to reload or refresh a web page.

Whenever we press the F5 key or any other key on the keyboard, certain keyboard events are triggered. In the event handler function, the event object contains details about the keyboard event. The event object has a key property that can reveal which key has been pressed by the user.

To keep things simple, we are going to monitor keydown event and in the event handler function, we will verify whether the F5 key is pressed or not.

In the following example, we have an input element.  As soon as the user presses the F5 key while typing in the input field, we will display a message on the screen. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 2 elements in the HTML file (div, and input).
  • The div element is just a wrapper for the rest of the elements. We are using style attribute with div element to center align the child elements.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
      
    <div style="text-align: center">
        <input type="text" placeholder="Enter Text">        
    </div>
    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have selected the input element using document.querySelector() method and stored it in the input variable.
  • We have attached keydown event listener to the input element.
  • In the event handler function, we are using if statement and key property of the event object to verify whether the F5 key is pressed or not. If yes, we will display an alert message.
let input = document.querySelector("input");

input.addEventListener("keydown", (e) => {         
  if (e.key === "F5") {
    alert('F5 Key Pressed')
  }
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •