Home > Net >  Why when the "cut" event fires, the input field is not empty yet?
Why when the "cut" event fires, the input field is not empty yet?

Time:09-30

The problem is that when I cut the text and the program reaches the "cut" event listener it never passes the if statement because inputField.innerHTML still is reading the previous value.

How could I overcome this behavior?

I have not idea how to google this, so I thought having it analyzed and explained by a human being would be a viable solution.

Thanks!

const inputField = document.querySelector(".input-field");

inputField.addEventListener("cut", () => {

console.log("getSelection: "   document.getSelection());
console.log("innerHTML: "   inputField.innerHTML);
  if (inputField.innerHTML === "") {
    console.log("I am here");
  }
});
.input-field {
  min-height:35px;
  width: 80%;
  font-size: 16px;
  padding: 5px;
  margin:5px;
  border: 2px solid #e6e6e6;      
}

[contenteditable="true"]:empty:before {
  content: attr(placeholder);
  pointer-events: none;
  display: block; /* For Firefox */
}
<div  placeholder="Tell me something..." contentEditable="true"></div>

CodePudding user response:

A more reliable solution is to compare the empty string with the textContent not innerHTML as the last contains an <br> element anyway, that's why the condition is not matching. Also, the event and DOM update does not run in the same microtask, so the updated content should be retrieved asynchronously, with queueMicrotask, or requestAnimationFrame for example:

const inputField = document.querySelector(".input-field");

inputField.addEventListener("cut", () => {
  console.log(inputField.innerHTML);
  requestAnimationFrame(() => {
    if (/^\n?$/.test(inputField.textContent)) {
      console.log("I am here");
    }
  });
});
.input-field {
  min-height:35px;
  width: 40%;
  font-size: 16px;
  padding: 5px;
  margin:5px;
  border: 2px solid #e6e6e6;      
}

[contenteditable="true"]:empty:before {
  content: attr(placeholder);
  pointer-events: none;
  display: block; /* For Firefox */
}
<div  placeholder="Tell me something..." contentEditable="true"></div>

  • Related