views:

53

answers:

1

I'm curious if anyone knows how I would trigger a function to run if/once the user finishes selecting text on the web page? I would like the user to be able to select text, and after a short delay(or immediately, at this point it doesn't matter much) an overlay button appears near the text that the user can then click and I go back and run more of my code that is based on the selection. This is for a Firefox extension.

A similar example that I can think of would be like in IE where you can select text and then it brings up the "web accelerators". I'm 99% sure I know how I would actually overlay the button, and get the position of the selected text, but I have no idea how to check to see if there is anything selected, without doing some sort of infinite loop, which just seems like a terrible idea.

Thanks in advance!

EDIT:

//In my overlay.js with the rest of my sidebar code
isTextSelected: function () {   
        var myText = cqsearch.getSelectedText();
        var sidebar = document.getElementById("sidebar");
        var sidebarDoc = sidebar.contentDocument || document;

        var curHighlightedDiv = sidebarDoc.getElementById("testDiv");
        curHighlightedDiv.innerHTML = "Current text selection:" + myText;
    }
};

//In my on firefox load function I added this
document.onmouseup = cqsearch.isTextSelected;

So this is what I have come up with using Robert's suggestion, and it took me some time getting everything in the right spot, but it works great! Now on to position my button. Thanks a ton!

+1  A: 

There isn't any onhighlightext or anything like that, but a solution would be to bind onmouseup to check if any text is selected if this isn't in a input/textarea.

Edit

Here's an implementation example for you. I only tested this in Chrome/Firefox/IE7. This works in inputs as well.

http://jsfiddle.net/qY7gE/

Robert
What objects 'onmouseup' How would I assign to? something like, window.onmouseup = myFunction(); ?
Robert Smith
Whatever you want to monitor, if you want to monitor the entire window, use window.onmouseup
Robert
Added an example for you, see my edit.
Robert
A disadvantage of this approach is that it doesn't work when a user selects text using the keyboard (Shift+→, etc.).
Marcel Korpel
@Marcel Korpel: In some sort of `textarea` or `input`, yes, but you could use the `onselect` event for those.
Robert
@Robert, fantastic this sounds like it would work really well! I'm going to try to implement it, and will end up marking as answered later today, early tmrw. Thanks! @Marcel I'm not sure if I need it, so this should work well. Thanks for the heads up though!
Robert Smith