javascriptaddeventlistenerkeydownkeyuptypescript

what is difference between working of keyup and keydown in javascript?


I have been just learning the keypress events in javascript and wonder why do i get different result in keyup and keydown. for eg. if i assign an input with an id and pass through it a addEventListner[reffer code] then if i type "1234" in keydown event i get output as "123" and this issue doesnt happens with keyup event.

in short i just wanted to ask that why in case of keydown no of character(typed in input) is not equal to no. of character displayed in output. this doesnt happens with keyup and which one should i use?

<!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>
    <input type="text" name="" id="in" placeholder="enter a value" style="border: solid; margin: 15px; padding: 5px">
<div style="border: 5px solid black; margin:10px; width:30vw; height: 15vh">
       Keydown result: <div id="keydown"></div>
</div>
<div style="border: 5px solid black; margin:10px; width:30vw; height: 15vh">
        Keyup result:<div id="keyup"></div>
</div>
</body>
</html>

<script>
document.getElementById('in').addEventListener('keydown', runevent);

function runevent(e){
   
    document.getElementById('keydown').innerText = e.target.value;
    
}

document.getElementById('in').addEventListener('keyup', runevent1);

function runevent1(e){
   
    document.getElementById('keyup').innerText = e.target.value;
    
}


</script>

Solution

  • in short i just wanted to ask that why in case of keydown no of character(typed in input) is not equal to no. of character displayed in output. this doesnt happens with keyup and which one should i use?

    If you're interested in characters, use keypress if you want to handle the character generated by the events, or use input if you just want the latest field value.

    This may help you see the sequence:

    const input = document.getElementById("field");
    const output = document.getElementById("output");
    
    function handleEvent(e) {
        output.insertAdjacentHTML("beforeend",
           "<pre>" + e.type + ": " + input.value + "</pre>"
        );
    }
    
    input.addEventListener("keydown", handleEvent);
    input.addEventListener("keyup", handleEvent);
    input.addEventListener("keypress", handleEvent);
    input.addEventListener("input", handleEvent);
    #output pre {
        margin-top: 0;
        margin-bottom: 0;
    }
    <input type="text" id="field">
    <div id="output"></div>