Wykrycie klawiszy w javascript

Ważna uwaga, wg. https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event keypress event zostaje porzucony i nie będzie dalej wspierany, więc mimo, że może on działać jeszcze w chwili obecnej, lepiej go nie używać.

Poniżej przykład wypisywania kodu i znaku klawiszy:

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <input id="inp">
            <p id="printArea"></p>
        </div>
    </div>

    <script type="text/javascript" src="main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>
function init(){
    document.getElementById("inp").addEventListener("keydown", logKey);
}

function logKey(event){
    printArea.setAttribute('style', 'white-space: pre-line;');
    printArea.textContent += "event.which:" + event.which;  // numer
    printArea.textContent += " event.key:" + event.key;     // znak
    printArea.textContent += " event.code:" + event.code;   // kod klawisza
    printArea.textContent += '\r\n';  
}
document.addEventListener("DOMContentLoaded",init,false);
Scroll to Top