I have a div
whose contents the user can edit via the contenteditable
attribute. When the user types something in the div, a function is called. I am using the oninput
event to trigger that function, since onkeydown
doesn't work with some of the stuff the function is supposed to do.
I also have bold, italic, and underline buttons that allow the user to style the text accordingly, via document.execCommand()
.
My problem: The function triggered oninput should not be triggered when the user uses the buttons to style the text. But that is what is happening. Is there any way I can prevent it?
Here's my code:
Note: For this example, I simplified the function triggered oninput. In reality, it will do a lot more than just changing the innerHTML
of an element.
document.getElementById("editableDiv").focus();
function boldText () {
document.execCommand("bold");
}
function myFunction () {
document.getElementById("feedback").innerHTML="The content was changed."
}
body {
padding: 10px;
font-family: sans-serif;
}
input {
padding: 5px;
outline: 0;
font-weight: bold;
}
div {
margin: 10px 0;
width: 200px;
border: solid 1px #000;
padding: 5px;
}
<input type="button" value="Bold" onclick="boldText();">
<div id="editableDiv" contenteditable="true" spellcheck="false" oninput="myFunction();">
Hello, World!
</div>
<p id="feedback"></p>
I added an If Statement to the function, making it only work if event.inputType != "formatBold"
:
function myFunction() {
if (event.inputType == "formatBold") {
document.getElementById("feedback").innerHTML = "The text was stylized.";
} else {
document.getElementById("feedback").innerHTML = "The content was changed.";
// + other things the function is supposed to do.
}
}