CyberJunkie
CyberJunkie

Reputation: 22674

Jquery get highlighted text in Redactor text editor

I'm using a fantastic jquery text editor named Redactor. I'm trying to add a new button which when clicked gets the text that was highlighted in the text editor.

The script allows 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 highlighted text

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

I thoroughly looked in the documentation and there's no way to get 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 it and would be best to use that.

In the script I found where the text selection function is on line 1719 but can't figure out how to use it for a custom button.

Anyone experienced with Redactor, please help!

Upvotes: 4

Views: 3037

Answers (3)

CyberJunkie
CyberJunkie

Reputation: 22674

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

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

Upvotes: 4

Generic Human
Generic Human

Reputation: 6117

Pick your poison (both methods work on Firefox and IE):

Method 1: Undocumented internal function

There is an internal function named getSelection, but it isn't part of the public API.

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

Method 2: Duplicating functionality

Now if you don't want to rely on accessing the internals of Redactor, you can duplicate the implementation into your own function, replacing access to internal variables with a 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 upside is that you are protected from changes in how internal functions of Redactor are named and called, but the downside is that your code is no longer browser-independent.

Upvotes: 8

strah
strah

Reputation: 6722

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

Try this:

Upvotes: 3

Related Questions