how to call function after text is selected

1.5k views Asked by At

I want to call function after text is selected in the document. Following code is not working

var showSelWin = document.getElementById('innerwindow');
var txt = ' ';
if (document.getSelection) function(){
txt = document.getSelection();
showSelWin.innerHTML = txt;
document.body.insertBefore(showSelWin, document.body.firstChild);}
1

There are 1 answers

0
RASG On

The document.getSelection method works differently in Google Chrome, Safari and Internet Explorer than in Firefox and Opera.

It returns a string in Firefox and Opera, and returns a selectionRange object in Google Chrome, Safari and Internet Explorer (the document.getSelection method is identical to the window.getSelection method in Google Chrome, Safari and Internet Explorer).

In Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, use the window.getSelection method and the toString method of the selectionRange object returned by the window.getSelection method to get the text content of the selection.

In older Internet Explorer versions, use the createRange method of the selection object and the text property of the TextRange object returned by the createRange method to get the text content of the selection.

a working sample for you: http://jsfiddle.net/uX628/

function GetSelectedText () {
    if (document.getSelection) {    // all browsers, except IE before version 9
        var sel = document.getSelection ();
        // sel is a string in Firefox and Opera,
        // and a selectionRange object in Google Chrome, Safari and IE from version 9
        // the alert method displays the result of the toString method of the passed object
        alert (sel);
    }
    else {
        if (document.selection) {   // Internet Explorer before version 9
            var textRange = document.selection.createRange ();
            alert (textRange.text);
        }
    }
}