0

So I have two input fields and some JavaScript code that writes the current value after each keystroke into a paragraph element. Now, if we use the KeyUp event, everything gets updated immediately but if we use KeyDown we observe that we only see the last n-1 characters after the n-th keystroke. Why is that?

var inputOne = document.getElementById("inputOne");
var pOne = document.getElementById("pOne");
var inputTwo = document.getElementById("inputTwo");
var pTwo = document.getElementById("pTwo");

inputOne.addEventListener("keydown", event => {
  pOne.innerHTML = event.target.value;
});

inputTwo.addEventListener("keyup", event => {
  pTwo.innerHTML = event.target.value;
});
#pOne {
  border: 1px solid green;
}

#pTwo {
  border: 1px solid red;
}
<div id="exercise">
  <div>
    keydown <br> inputOne) <input id="inputOne" type="text"> pOne)
    <p id="pOne"></p>
  </div>
  <div>
    keyup <br> inputTwo) <input id="inputTwo" type="text"> pTwo)
    <p id="pTwo"></p>
  </div>
</div>

JsFiddle Example: https://jsfiddle.net/45gshtom/2/

VLAZ
  • 26,331
  • 9
  • 49
  • 67
handy
  • 696
  • 3
  • 9
  • 22
  • 1
    because the event is being triggered.... https://www.quirksmode.org/dom/events/keys.html – epascarello Sep 18 '19 at 12:36
  • I did come across that site before posting but I don't get it. I seem to have a very wrong understanding of what happens here. **Case 1:** We press a key, the key is down, the event fires which now updates the innterHTML with the value from the input (which is present in the input). **Case 2:** We press a key, the key is down and the value is set in the input and we release it, now the event fires and the innerHTML is set using the value again. So I expect both to update immediately – handy Sep 18 '19 at 12:44
  • 1
    keydown is so you can detect what key is pressed and cancel it before it does its thing. `keydown` is the start of you pressing the key. `keypress` is fired each time the character is inserted (so if you hold down the key, it fires multiple times.) `keyup` is fired when you let go of the key. – epascarello Sep 18 '19 at 12:45
  • @epascarello Okay, so the value isn't set in the input field and everything makes sense. Is there a more in depth article about this? Like how that event system and e.g. the "write the value of the key I pressed down into the input fiel" are connected? What comes first etc.? Also if you write your comment into an answer I could accept it. – handy Sep 18 '19 at 12:48

0 Answers0