tags:

views:

89

answers:

3

how to detect text selection from a text search using the browsers Ctrl+F.

for example i want to make a FAQ, where are the items are closed (to remove clutter), and clicking them opens the text within them, but at the same time i dont want Ctrl+F to be killed off. So im thinking, is there a way for javascript to detect that i have searched for some text within a non visible (but selectable) block of text, and to automatically open it.

so is it even possible to detect text selection from a search with Ctrl+F? if it is, then how?

edit: ok for example i have a div with the id of "one" and a div with the id of "two" both have their own text

<div id="one">Google is a search engine</div>
<div id="two">Stackoverflow users are very informative</div>

both have their text hidden from view but still selectable, but not by mouse (using margins or covering)

so a user searches for "Stackoverflow" on this page, i want to trigger a javascript function upon the search selection (how??), and i need the function that runs to know which div, with what ID has some text selected.

i hope its clearer now :S

+1  A: 

As far as I know, there is no way. The content of the search field entirely under the control of the browser, and you can't access this from within the page.

What you might be able to do however, is detect a selection in the document and react to that. This will however probably produce many false positives (because you can't distinguish between an ordinary selection and a search), and it won't work with browsers that do not use an ordinary selection to highlight search results.

More info on detecting selections: Introduction to Range on Quirksmode

Pekka
it does not matter what the selection type is, as long as i know it has been selected.
YuriKolovsky
+2  A: 

This is browser dependent. In Chrome (maybe Webkit in general?), it seems to use a selection that is separate from the one in the DOM API.

However, Firefox will use the DOM selection when highlighting text from a Ctrl+F.

For example, go to google.com, and type this in Firebug:

window.getSelection().toString()

This will return ""

Now do a Ctrl+F, type in Privacy, press enter.

Enter the above command again in Firebug, and you will get:

"Privacy"

Matt
thanks for those details firebug does indeed show that, but i meant detecting that the text within a <div id="something"> was searched for, not what text was selected while searching.
YuriKolovsky
+1 good info, didn't know this.
Pekka
A: 

Why not make the FAQ search friendly and use a service for that. Google Custom Search Engine might be a good place to start.

mjboggess