I am trying to make text bold in a content editable by a button click.
const e = document.querySelector('#e');
const b = document.querySelector('#b');
e.addEventListener('input', (event) => {
console.log('---');
console.log('isTrusted', event.isTrusted);
console.log('inputType', event.inputType);
});
b.addEventListener('click', (event) => {
e.dispatchEvent(new InputEvent('input', {
bubbles: true,
cancelable: true,
composed: true,
inputType: 'formatBold',
}));
});
<button id="b">B</button>
<div id="e" contenteditable="true">
Hello World
</div>
I’m testing in Safari on MacOS:
If I highlight the word hello, right-click, select “Font” from the menu, then select “Bold”, the highlighted word hello will bold. I will also see the input event as expected.
If I highlight the word hello, click the “B” button, the highlighted word hello will not bold. I still see the event as expected (but it is not trusted).
How do I dispatch an input event and have it work?
