darksmurf
darksmurf

Reputation: 3967

Event listener for command value

I've built a rich text editor using contenteditable and have a button for making the text bold by executing document.execCommand("bold"). I want to style the button differently when this command is active (meaning the next character I write is going to be bold). A hack would be to excessively check document.queryCommandValue("bold"), but I'm hoping there is a better solution.

Is there any way to listen to when the value of document.queryCommandValue("bold") changes?

Upvotes: 3

Views: 643

Answers (2)

Rango
Rango

Reputation: 3907

I think that the best solution might be listening for selectionchange event on the document object.

document.addEventListener('selectionchange', () => {
  toolbar.boldButton.classList.toggle('active', document.queryCommandState('bold'))
})

Note that this event is fired only on the document object, and never on the "contenteditable" element.

Upvotes: 0

Motla
Motla

Reputation: 1230

You can check for the computed style at caret position and update your buttons accordingly:

// Get your contenteditable
var my_editor = document.getElementById("my_editor");

// Declare the function to update your buttons
function update() {
  // getting style at caret position
  var sel = window.getSelection();
  var style = sel.focusNode && window.getComputedStyle(sel.focusNode.parentElement);

  // guessing if text is bold
  var fW = style.fontWeight;
  var is_bold = fW && (parseInt(fW) > 400 || fW.indexOf("bold") == 0);

  // updating your buttons accordingly
}

// Bind the function to useful events
my_editor.addEventListener("input", update); // when content is modified
my_editor.addEventListener("click", update); // when caret is changed with the mouse
my_editor.addEventListener("keyup", update); // when caret is changed with the keyboard arrows

Upvotes: 2

Related Questions