Jquery gets selected text in a Redactor text editor

I am using a fantastic jquery text editor called Redactor . I am trying to add a new button that, when clicked, gets the text highlighted in a text editor.

The script allows you to add a new button by adding the following setting:

buttonsCustom: { button1: { title: 'Button', callback: testButton //executes callback on button click } } 

then in the callback I want to get the selected text

 function testButton(obj, event, key) { alert(highlighted_text); } 

I carefully looked through the documentation and could not get the highlighted text. I tried other functions like ...

 function getSelText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } else return; return txt; } 

... but the text editor script already has a way to do this, and it would be better to use it.

In the script, I found that the text selection function is on line 1719, but cannot figure out how to use it for a custom button.

Anyone running into Redactor help!

+4
source share
3 answers

Choose your poison (both methods work in Firefox and IE):

Method 1: undocumented internal function

There is an internal function called getSelection , but it is not part of the public API.

You can call it with $('#redactor_content').data('redactor').getSelection() .

Method 2: Duplicate Functionality

Now, if you do not want to rely on access to the internal components of Redactor, you can duplicate the implementation in your own function by replacing access to the internal variables with the call to getDoc() :

 function getRedactorSelection(elem) { var doc = elem.getDoc().get(0); if (doc.getSelection) { return doc.getSelection(); } else if (doc.selection) { return doc.selection.createRange(); } }; 

Usage: getRedactorSelection($('#redactor_content'))

The surface is that you are protected from changes in the way Redactor's internal functions are called and called, but the disadvantage is that your code is no longer browser dependent.

+8
source

UPDATE: Redactor added a new function to get the selected html.

$('#redactor').getSelected();

+4
source

You will probably need the following: $('#redactor_content').getDoc()[0].getSelection();

Try the following:

+3
source

All Articles