Alex-D / Trumbowyg

A lightweight and amazing WYSIWYG JavaScript editor under 10kB
https://alex-d.github.io/Trumbowyg
MIT License
4k stars 614 forks source link

Inserting html tags around highlighted text #1423

Open gpack opened 1 year ago

gpack commented 1 year ago

Hi,

I'm trying to wrap some HTML around highlighted text in the editor. Reason for this is because I have a font size "slider" above the editor, so when the user slides to a specific font I would like to only resize the highlighted words (not all the text). So I'm thinking best way to do this is to fetch the highlighted text in the editor, wrap it with a "span" tag (that has a css class) and replace the selected text.

What's the best possible way to do this?

Currently I tried using trumbowyg('restoreRange') and trumbowyg('getRangeText') to grab the highlighted text. But there are some small issues with that:

  1. It only fetches a plain text version of the highlighted text, it doesn't seem to return any or tags so I lose any custom colors that text might have had using tags.
  2. When I use execCmd to "insertHTML" to replace the highlighted text, it inserts it once, and then it no longer is selected and therefore "getRangeText" doesn't work the second time (when user slides the font-slider again).

I'm using the below code to replace the highlighted text:

$('#input-textarea-edit').trumbowyg('restoreRange');
$('#input-textarea-edit').trumbowyg('saveRange');
var range = $('#input-textarea-edit').trumbowyg('getRangeText');

const htmlValue = '<span class="' + $newFontSize + '">' + range + '</span>';
            $('#input-textarea-edit').trumbowyg('execCmd', {
                cmd: 'insertHTML',
                param: htmlValue,
                forceCss: false
            });

Any help how to do this properly would be very appreciated.

thanks.