473,503 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Got selected text, but can I get surrounding context?

Hi all...

I am able to grab the text that a user has selected on a web page,
using this code:

function moreInfo() {
if (!isIE) {
var t = window.getSelection();
// act on variable "t";

} else if (document.selection && document.selection.createRange) {
var t = document.selection.createRange();
if (document.selection.type == 'Text' && t.text>'') {
document.selection.empty();
// act on variable "t";

}
}
}

(the boolean "isIE" is established earlier in the code)

This works. However, I'm wondering how to get the words *around* the
selected word. Take these sentences for example: "If you need to
framglubble the zartbox, then you should buy the red widget.
Otherwise you can buy the blue widget and save some money."

My code will tell me if the person has selected the word "widget".
But I'd like to know if the selection is after "red" or "blue". Is
this possible? I've been scouring the Internet for some advice, and
I'm having trouble finding an answer.

Many thanks in advance for your time.

Feb 22 '07 #1
3 2530
VK
On Feb 22, 7:39 pm, "Dekortage" <dekort...@gmail.comwrote:
My code will tell me if the person has selected the word "widget".
But I'd like to know if the selection is after "red" or "blue". Is
this possible?
Not in any straightforward way AFAIK.

You may extend/shift range left or right to see what words will be
added. In any case it presumes some fixed content you know in advance
so able to recognize by fragments. In this case wouldn't it be much
more easy to mark all needed segments in advance? Just a suggestion:

<p>If you need to framglubble the zartbox, then you should buy the
<span onclick="f(this)">red widget</span>.
Otherwise you can buy the <span click="f(this)">blue widget</spanand
save some money.</p>

Feb 22 '07 #2
On Feb 22, 3:36 pm, "VK" <schools_r...@yahoo.comwrote:
You may extend/shift range left or right to see what words will be
added. In any case it presumes some fixed content you know in advance
so able to recognize by fragments. In this case wouldn't it be much
more easy to mark all needed segments in advance? Just a suggestion:

<p>If you need to framglubble the zartbox, then you should buy the
<span onclick="f(this)">red widget</span>.
Otherwise you can buy the <span click="f(this)">blue widget</spanand
save some money.</p>
Thanks for your response, VK.

I hear ya. I have specific reasons for doing it the other way. I'm
trying to develop a definition system so someone can select text on a
page and hit button to get a definition. Using the example above,
they could select "widget" or "framglubble" or "money". But there are
many words which have different meanings depending on context, so the
definition system could be more accurate/useful if I could
intelligently scan context.

I'm intrigued about shifting the range to the left. I expect to be
working with fairly fixed content (or at least indexable content that
would be intelligently tied to the definition system). How would I do
that?
Feb 22 '07 #3
Okay. I have a really rough, unoptimized version of what I want. The
IE part is pretty simple, since it can move the selection boundary
range around. The Mozilla part is a bit more of a hack: I get the
full text of the node that the selection resides in, then based on the
selection offset within the node, I chop up the text around it to
determine the words just before and after the selected word. It
doesn't work quite perfectly, but it's close. It doesn't work with
Safari but I've tested it succesfully with Firefox (Mac) and IE 6
(Windows). (Safari has some weird text range issues...?!?)

Below is the code for an entire HTML page. Hopefully the word wrap
won't kill it. I freely admit it is an ugly, unoptimized hack thrown
together as a proof of concept, so you're welcome to clean it up, fix
bugs, add features, etc.


<html>
<head>
<title>Framglubble the Zartbox: getting selection context via
JavaScript</title>
<script language="javascript">

// Original author: Dekortage @ a server called Gmail.com
// You're free to copy this but leave the "Original author" line
intact.
//
// This deliberately returns a "null" value if it determines that the
previous
// or next word is separated from the selected word by a comma or
period.

// determine browsers
var isIE = document.all;
var isN6 = document.getElementById && !document.all;
var isN4 = document.layers;
var detect = navigator.userAgent.toLowerCase();
var isSafari = ( detect.indexOf("safari") 0 );

function trim(x) { return x.replace(/^\s*|\s*$/g,''); }

function moreInfo() {
if (!isIE) {
var t = window.getSelection(); // selected text
tx = t+"";
preWord = null;
postWord = null;

if (!isSafari) { // Safari does not work with this

origNode = t.anchorNode;
orig = origNode.textContent + "";

// get previous word
preTxt = orig.slice(0,t.anchorOffset);
preArray = preTxt.split(" ");
preCount = preArray.length;
while ((preWord == null) && (preCount >= 0)) {
preCount -= 1;
if ((preArray[preCount] != null) && (preArray[preCount] != "") &&
(preArray[preCount] != " ")) {
preWord = preArray[preCount];
if ((preWord.charAt(preWord.length-1) == ",")) preWord = null;
}
}

// get next word
postTxt = orig.slice((t.anchorOffset + tx.length + 1));
postArray = postTxt.split(" ");
if ((postArray[0] != ".") && (postArray[0] != ",") &&
(postArray[0] != "--") && (postArray[0] != "") &&
(postArray[0] != " ")) { // if not end of sentence
postWord = postArray[0];
}

}

showWords(tx,preWord,postWord);

} else if (document.selection && document.selection.createRange) {
var t = document.selection.createRange(); // selected text
if ((document.selection.type == 'Text') && (t.text '')) {

tx = trim(t.text);

t.moveStart("word",-1); // not sure why t.move() alone wouldn't work
t.moveEnd("word",-1);
preWord = trim(t.text);
if ((preWord == ",") || (preWord == ".")) {
preWord = null;
}

t.moveEnd("word",2);
t.moveStart("word",2);
postWord = trim(t.text);
if ((postWord == ",") || (postWord == ".")) {
postWord = null;
}

// need to fix this to work with hyphenated words

document.selection.empty();
showWords(tx,preWord,postWord);
}
}
}

function showWords(t,a,z) { window.alert("Sequence: "+a+","+t
+","+z); }

if (isIE) document.ondblclick=moreInfo;

</script>
</head>
<body ondblclick="if (!isIE) moreInfo()" style="font-size: 24px;
margin: 24px;">
<p>If you need to framglubble the zartbox, then you should buy the red
widget. Otherwise you can buy the blue widget and save some money.</p>
<p>(double-click on a word to see its context)</p>
</body>
</html>

Feb 23 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2118
by: worzel | last post by:
Can't suss this out for the life of me, googling of no help either. Okay, new to win forms; I have a treeview with several root nodes, each having a single level of child nodes underneath. I also...
3
2435
by: gooderthanyou | last post by:
I have a textfield and you of course you can select text... When they hit the bold button I want it to obtain the selected text and bold it, the hard part is trying to figure out if javascript...
3
3859
by: brisco5 | last post by:
I have a TEXTAREA element. A user right clicks within in to get the context menu and they select "paste". I want my javascript code to know that they selected "paste". I know you can capture the...
2
15361
by: paolol | last post by:
Hi, I wont to get the current row values from a dataset, any one know how to reach those data ?? At the moment I use a work around, but it's not good .. foreach (DataRow row in...
20
5574
by: Jukka K. Korpela | last post by:
I recently noticed, once again, how the common implementation of italics can really disturb. I'm referring to the common phenomenon that there is by default too little spacing after italics text,...
2
2435
by: travelrats | last post by:
Hi Here's my problem - I've been trying to figure this out for a while and ran out of ideas... <div> id1 contains <div> id2 (a geographical map) <div> id2 contains a context menu made out of...
7
2984
by: active | last post by:
In control panel/Display/Appearance/Effects if : 'Use the following method to smooth edges of screen fonts' is checked and ClearType is selected in the combobox (no problem if Standard is...
4
4191
by: Karl | last post by:
Hi all, I want to write an application that is launched from the context menu in Windows Explorer/Computer. That is to say, when I am browsing around my hard drive and get to any location I...
0
3274
by: divya1949 | last post by:
Create a windows c# application which will Read a xml file and populate nodes in the treeview. 1 On selection of treenode display the child nodes of that node in listview control 2. ...
0
7074
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7322
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
5000
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4667
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3161
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1501
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
374
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.