Charles K Livingston
Charles K Livingston

Reputation: 25

Keydown function runs before character is printed to screen?

I have an element that sits above 3 elements with the same class. When I type into one of the content editable divs, it expands the element if the width goes beyond its original. I want to set the above element to equal the same width as the other 3.
The issue I am running into is that when I run the keydown() function, it runs before the actual character is printed to the screen, thus the width is always one character too large, or small. If I run the keyup() function then it is delayed and is clunky because the character is printed to the screen before my finger unpresses the key. How do I remedy this? Is there a way to run the function when the key is printed?

$(".tr1").keydown(function() {
var elements = document.getElementsByClassName('tr1');
var totalWidth = 0;
for (var i = 0; i < elements.length; i++) {
totalWidth += elements[i].offsetWidth;
}
document.getElementById("qa-checklist").style.width=''+totalWidth+'px';
            });

I added a stackblitz:
https://js-ic8uy7.stackblitz.io

Upvotes: 0

Views: 52

Answers (1)

Lemondoge
Lemondoge

Reputation: 989

The oninput event seems to not have this issue.

<label for="test">Using oninput:</label>
<input type="text" id="test" oninput="console.log(this.value)"></input>

EDIT: To do this in your example, replace "keydown" with "input":

document.addEventListener('input', function(event) {
        console.log("change");
        var elements = document.getElementsByClassName('tr1');
        var totalWidth = 0;

        for (var i = 0; i < elements.length; i++) {
            totalWidth += elements[i].offsetWidth;
        }
        console.log(totalWidth);
        document.getElementById("qa-checklist").style.width=''+totalWidth+'px';
    });
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}
.rowcell {
  outline: grey;
  border: 1px solid black;
  min-width: 50px;
}
#qa-checklist {
  display: inline-block;
  width: 1px;
  border-bottom: 50px solid black;
}
<div id="qa-checklist"></div>
<div style="display:flex;">
    <div class="rowcell tr1" contenteditable="true"></div>
    <div class="rowcell tr1" contenteditable="true"></div>
    <div class="rowcell tr1" contenteditable="true"></div>
</div>

Upvotes: 2

Related Questions