1

I am writing some code to find the user selection in a contenteditable div, I'm taking my code from this quirksmode article.

function findSelection(){
  var userSelection;
  if (window.getSelection) {userSelection = window.getSelection;} 
   else if (document.selection){userSelection = document.selection.createRange();} // For microsoft
  if (userSelection.text){return userSelection.text} //for Microsoft
   else {return userSelection} 
  } 

I'm testing it in Chrome and Firefox, if I do an alert(userSelection) within the function or an alert(findSelection();) outside the function, it returns function getSelection() {[native code]}. If I do console.log(findSelection();) it gives me getSelection(). Is there something I've done wrong?

skaffman
  • 398,947
  • 96
  • 818
  • 769
DavidR
  • 5,350
  • 6
  • 30
  • 36

3 Answers3

3

getSelection is a function... you need to execute it to get the selection?

if (window.getSelection) {userSelection = window.getSelection();}
lunixbochs
  • 21,757
  • 2
  • 39
  • 47
1

Change it to

  if (window.getSelection) {userSelection = window.getSelection();}

(getSelection())

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

This is to get the text of the selection. Even with the typo fixed, you've got inconsistent behaviour: IE is returning the selection's text as a string while other browsers will return a Selection object that will give you the selection text string only when its toString() method is called.

The following would be better:

function getSelectionText(){
    if (window.getSelection) {
        return "" + window.getSelection();
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange().text;
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536