简体   繁体   中英

keydown not triggering until key pressed twice

so i have a div I'm trying to toggle the class of depending on if a another div is empty or not.

currently with key down when a key is pressed nothing happens, and then when a second key is pressed the display style is switched to none.

this is the same for when text is removed in the div, when the div is empty it does not switch back to display block, but when backspace is pressed again (once already empty), then the display value is changed back to block.

Any thoughts?

HTML

  <div id="textbox">
    <div id="colon" class="consoleText consoleArea"><span class="consoleIcons">&#10132;</span></div>
    <div role="textbox" contenteditable="true" id="navtype" class="consoleText" tabindex="0" style="margin-left: 40px" onkeypress="return (this.innerText.length <= 37)" onpaste="return false;" spellcheck="false"></div>
    <div class="consoleText"><span id="caret"></span></div>
    <div class="placeholder">type here to change directory</div>
  </div>

JavaScript

let consoleMsg = document.getElementById("navtype");

let consoleText = document.querySelector("[contenteditable]");

consoleText.onkeydown = function () {
if (consoleText.innerText) {
    let placeholder = document.querySelector(".placeholder");
    placeholder.style.display = "none";
  } else {
    let placeholder = document.querySelector(".placeholder");
    placeholder.style.display = "block";
  }
};
if(consoleText.innerHTML !== null || consoleText.innerHTML !== "" || consoleText.innerHTML !== undefined) {
   let placeholder = document.querySelector(".placeholder");
   placeholder.style.display = "block";
} else {
  let placeholder = document.querySelector(".placeholder");
  placeholder.style.display = "none";
}

The best way to check content of a DIV is innerHTML. Your code should listen to triggeringElement.innerHTML instead of keydown event. If the input element is go for triggeringElement.value.

The issue was using.onkeydown - what I should of used was.oninput -

.onkeydown seems to have a delay the function is fired before the input is added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM