Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 356
CyberJunkie Avatar asked Dec 06 '22 13:12

CyberJunkie


1 Answers

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.

like image 93
Generic Human Avatar answered Dec 27 '22 12:12

Generic Human