views:

130

answers:

3

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?

+2  A: 

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

if (window.getSelection) {userSelection = window.getSelection();}
lunixbochs
+1  A: 

Change it to

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

(getSelection())

SLaks
ar, just a typo, thanks, I'll be more careful next time.
DavidR
A: 

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