Pezcraft
Pezcraft

Reputation: 299

Is there a way to determine if execCommand('bold') is being executed right now?

I am building a simple JavaScript text editor with a bold function. I am using execCommand('bold') for this. For the bold-icon in the toolbar I have to check if I am writing bold right now. I was thinking of a boolean variable which is being set everytime I execute the command, but this is not possible since text can be selected and so on.

So is there a way to determine if execCommand('bold') is being executed right now?

Upvotes: 1

Views: 1475

Answers (1)

Kaiido
Kaiido

Reputation: 137054

You want the Document.queryCommandState() method.

bolder.onclick = e => {
  document.execCommand('bold');
};

inp.onfocus = document.onselectionchange = e =>
  bolder.classList.toggle('active', isWritingBold());

function isWritingBold() {
  return document.queryCommandState('bold');
}
#bolder.active::before {
  content: 'un-';
}
<button id="bolder">boldify current selection</button>
<div id="inp" contenteditable>edit me and <b>boldify</b> any part of my content</div>

Upvotes: 1

Related Questions