views:

355

answers:

2

NOTE: Solved my own problem, it seems. See the edits.

I am trying to write a greasemonkey script that will highlight all the matching texts on the page when the user selects a text, and then remove the highlighting when the selection is canceled. I am looking for a jQuery way to do this. It seems like there is a select event in the jQuery core, but I couldn't get it to work they way I wanted it. Try running the following on this page for instance:

$(document).select(function () { 
      console.log("hey");
  });

There is no response. So it seems that I need to attach this to text nodes in particular. But that doesn't seem practical to me. It would be way too slow.

Any suggestions, ideas? Thanks.

EDIT # 1:Ken Browning pointed out that the select event in jQuery only fires in textarea and input fields. So I guess I have to abandon that. Maybe I can change my question slightly, and ask if anyone can tell me the javascript way to bind selection events to all the text nodes.

EDIT # 2: I think I found part of my answer. This returns the selected text on the page, but you still have to click a button to show it. There is no select event binding. Hm.

<script language=javascript>
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {//javascript select event
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return;
document.aform.selectedtext.value =  txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">

http://www.codetoad.com/javascript_get_selected_text.asp

EDIT # 3: SO I bound to the mouseup event rather than to selection. I am then checking the value of the getSelText() to proceed further after that point. Yay!

EDIT # 4: In case anyone is curious, I posted my finished script on Userscripts. Here is the link. Enjoy!

http://userscripts.org/scripts/show/55148

+1  A: 

The select event fires when a user selects some text in a text field, including input and textarea.

I read that to mean you've got the wrong event unless your page contents are in an <input type="text"> or a <textarea>

Ken Browning
ah. I didn't notice that. Thanks.
picardo
+2  A: 

In Firefox, document.getSelection() will return the selected text.

You could attach an onmouseup handler to the document, and check for the selection each time you receive a mouseup event.

Note: After I wrote this, you posted some source code to get the selection. While that code is fine (and cross-browser), if you’re using Greasemonkey you must be on Firefox, so all you need is document.getSelection().

Nate
awesome. Thanks for the informative comment.
picardo
if (document.selection // IE - not that its needed for greasemonkey, but might be handy
gnarf