views:

59

answers:

1

I'm trying to write a bookmarklet that grabs any selected text on a web page and sends it to my website. It should (hopefully) work in Chrome, FFX, Safari, and IE. I did a search and found a function, but it doesn't appear to work. Here is the code:

<html>
<body>
<div onClick=getSelText()>Click</div>
<div>please select me</div>
</body>
<script language=javascript>
function getSelText(){
    var txt = 'nothing';
    if (window.getSelection){
        txt = "1" + window.getSelection();
    } else if (document.getSelection) {
        txt = "2" + document.getSelection();
    } else if (document.selection) {
        txt = "3" + document.selection.createRange().text;
    } else return;

    alert("selected text = " + txt);
}
</script>
</html>

when I select the text in the div "please select me" and hit the click div, I just get "selected text = 1"

thanks

A: 

When you click the div, you deselect the text, so selection is ''. If you select part of "Click" text it should work. Or if you select something and type "javascript: getSelText()" in the address bar.

hamax
makes perfect sense. thanks!
phil swenson