2

I have a contentEditable div for implementing a Rich Text Editor as in:

     <div contenteditable="true"></div>

I have a drop-down select list to apply a font. I am using execCommand with the fontName option to do so. After selecting some text, when I click on the select button, I lose the selection of the text inside the contentEditable div. Admittedly, I am weak in browser-side Javascript. Is there a quick way around this issue?

  $(document).on('click', '#specificFont', function (e) {
     ...
     // tried e.preventDefault() here
     ...
     //Code to get the exact font name 
     ...
     execCommand('fontName', null, exactFontName);

  });

I tried with mousedown event and with e.preventDefault() too.

I want that the selection is retained when I click on the outside button so that execCommand has it to apply the font.

asinix
  • 966
  • 1
  • 9
  • 22
  • 2
    You could save the current selection position and the selection length in variables. Then after losing focus, you could *manually* re-select your text part thanks to your variables. – Kévin Bibollet Jul 08 '19 at 15:26
  • 1
    I believe the quickest and easiest way to achieve this is to do what @KévinBibollet said. [This](https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) might be helpful. – Tomasz Kasperczyk Jul 08 '19 at 15:28
  • 1
    @TomaszKasperczyk Yes. Both of you are right. Will need to understand the different API involved but thats what I was looking for. Surprisingly the "this" reference is 10 years old and still relevant with the API still intact. – asinix Jul 08 '19 at 15:59
  • preventDefault() works on FF but not on Chrome. I hate browsers. – capr Mar 03 '23 at 17:59

0 Answers0