irva91
irva91

Reputation: 35

Saving highlighted text to a string

I'm making a web application that splits the screen into two windows, with one side a web based text editor and the other side just a normal window. I am trying to find a way to be able to have a user highlight some text on the browser side and then auto-save the highlighted text into a string where I would then be able to manipulate the string.

Does anybody have any ideas? Any help would be greatly appreciated.

Upvotes: 2

Views: 2447

Answers (2)

catherine
catherine

Reputation: 22808

        function getSelectionText() {
            var text = "";
            if (window.getSelection) {
                text = window.getSelection().toString();
            } else if (document.selection && document.selection.type != "Control") {
                text = document.selection.createRange().text;
            }
            return text;
        }
        $(document).ready(function (){
           $('div').mouseup(function (e){
               alert(getSelectionText())
           })
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
        Hello, this is a highlight text test
    </div>

Upvotes: 5

mcanfield
mcanfield

Reputation: 897

So you'll have two steps here.

  1. Capture the mouseup event.
  2. Return the selected text.

Whatever text is selected on the document can be accessed via the js call:

window.getSelection()

But this is browser specific. So you can use this code snippet to cover grabbing the selected text from all browsers.

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

I assume you are using a library like jQuery. So that can help with the mouseup events. You probably don't want to capture selections on the whole document. So you could bind to whatever element you need. Something like my jsfiddle here: http://jsfiddle.net/xh799/

Upvotes: 2

Related Questions