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>
keydown
is fired before the input element is updated (and can be cancelled). See onKeyPress Vs. onKeyUp and onKeyDown – Machinist