473,624 Members | 2,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return character position on page?

Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9. Any thoughts?

Jul 23 '05 #1
5 2325
je*********@hot mail.com wrote:
Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9.


What a strange request:-)

To answer straightly, yes you can do it, first by retrieving the text of
the document, then by searching the chars within the text.

You have many ways to retrieve the text:
- documents are represented by trees of nodes (elements), which kind of
mirror the structure of your HTML page. What you can do is therefore to
identify the "text" elements, retrieve their value and concatenate all
values;
- some browsers (IE, Opera) offer an "innerText" property, which
directly gives the text contained in an element;
- some browsers (IE, Mozilla) support "text ranges", which are also a
good way to get the text from nodes.

Once you've retrieved the text you just have to apply string methods or
regular expressions to find your chars, but you won't be able to do much
afterwards (like highlighting or whatever).

Just out of curiosity, why do you exactly need the positions? Given the
structure of the DOM I cannot really think of a practical application.
<div>Hello, World!</div>
<div>This is my string</div>

<form action="">
<input type="text">
<input
type="button"
value="getCharP osition()"
onclick="alert( getCharPosition (this.form.elem ents[0].value));">
</form>

<script type="text/javascript">
var getCharPosition = (function(){
function getTextFromNode (node){
if(typeof node.innerText! ="undefined" ) return node.innerText;
else
return function(N){
for(var ii=0, s="", c=N.childNodes; ii<c.length;ii+ +) {
if(c[ii].nodeType==3) s+=c[ii].nodeValue;
else if(
c[ii].nodeType==1 &&
c[ii].nodeName.toLow erCase()!="scri pt"
) s+=arguments.ca llee(c[ii]);
}
return s;
}(node);
}

return function(token) {
if(
token.length>0 &&
document.body && (
typeof document.body.i nnerText!="unde fined" ||
document.body.c hildNodes &&
document.body.n odeName
)
){
var txt=getTextFrom Node(document.b ody).replace(/\r|\n/g,"");
var match;
var re=new RegExp(token, "gi");
var positions=[];
while((match=re .exec(txt))!=nu ll) {
positions[positions.lengt h]=match.index+1;
}
return positions.lengt h==0 ?
"No char found." :
"Char(s) found at " + positions.join( " - ");
} else {
return "Cannot find char position!";
}
}
})();
</script>
HTH,
Yep.
Jul 23 '05 #2
I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.

Jul 23 '05 #3
Lee
je*********@hot mail.com said:

I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.


And you're absolutely sure the page contents will never change?
Nobody will ever correct a typo, throwing off the character count?

Jul 23 '05 #4

Yes is doable, but to recall it once the page is gone from an object is
another matter, unless the hierarchy is kept intact, which may not be, but
the object you want for that is a Range object, make a Range object off
the selection, store to cookie with escaped() chars and all, and when the
page is visited again, check for the cookie and run a string query on
document.body childNodes. Mozilla and IE and Opera do Ranges.
Danny
On Thu, 09 Jun 2005 13:33:52 -0700, <je*********@ho tmail.com> wrote:
Is there a way to return the character position on a page? Not the x
and y coordinates, but the number of characters on a page. For
instance i have a html page with the following text: This is my string.
Then character postion for m would be 9. Any thoughts?


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #5
Yep
je*********@hot mail.com wrote:

Hi,
I am using it to store what a users selects or highlights within a html
page. That position plus the length of the highlight will then be
passed to an application to be stored so that when they revisit the
page, what the user selected will still be highlighted. The app needs
the postion on the page, as well as the length of the highlight.


I'm starting to see what you want, however I'm afraid you won't be be
able to do it the way you want, given the way the page is parsed
client-side: basically you manipulate nodes, not text.

What I can suggest is the following: capture the user selection, alter
the tree, store the altered tree in a DB with the username, and send
the altered tree back when requested by the user. The code below should
work in IE/Mozilla (slightly tested only, I'm on my way to holidays).

Given the nature fo the text to be highlighted, then you might consider
sending only a part of the tree, or even adopt a text-based highlight
(is there's no more than 1 occurrence of the text in your page - you
still don't tell the "real" why:-)).
---
<script type="text/javascript">
var SelectionManage r = (function() {
var MARKER_CLASS="m arkerClass";

function getSel(){
var sel=null;
if(
typeof document.select ion!="undefined " &&
document.select ion &&
document.select ion.type=="Text "
){
sel=document.se lection;
} else if(
window.getSelec tion &&
window.getSelec tion().rangeCou nt>0
){
sel=window.getS election();
}
return sel;
}

function createRange(){
var rng=null;
if(document.bod y && document.body.c reateTextRange) {
rng=document.bo dy.createTextRa nge();
} else if(document.cre ateRange) {
rng=document.cr eateRange();
}
return rng;
}

function moveRange(rng, el){
var moved=false;
if(rng.moveToEl ementText){
rng.moveToEleme ntText(el);
moved=true;
} else if(rng.selectNo deContents) {
rng.selectNodeC ontents(el);
moved=true;
}
return moved;
}

function selectRange(rng ){
if(rng.select){
rng.select();
} else if(window.getSe lection) {
var sel=window.getS election();
if(sel && sel.removeAllRa nges && sel.addRange) {
sel.removeAllRa nges();
sel.addRange(rn g);
}
}
}

function createRangeFrom Sel(sel){
var rng=null;
if(sel.createRa nge) {
rng=sel.createR ange();
} else if(sel.getRange At) {
rng=sel.getRang eAt(0);
if(rng.toString ()=="") rng=null;
}
return rng;
}

function markRange(rng){
var marked=false;
if(rng.pasteHTM L){
rng.pasteHTML(
"<span class='"+MARKER _CLASS+"'>"+rng .text+"<\/span>"
);
marked=true;
} else if(rng.extractC ontents){
var span=document.c reateElement("s pan");
span.className= MARKER_CLASS;
span.appendChil d(rng.extractCo ntents());
rng.insertNode( span);
marked=true;
}
return marked;
}

function createSelection FromNode(node){
var rng=createRange ();
if(rng){
if(moveRange(rn g, node)){
selectRange(rng );
}
}
}

document.onmous eup = function(evt){
var sel=getSel(), rng;
if(sel) {
rng=createRange FromSel(sel);
if(rng) {
SelectionManage r.lastSelection =rng;
}
}
}

return {
lastSelection : null,
markLastSelecti on : function() {
return this.lastSelect ion && markRange(this. lastSelection);
},
highlightSelect ion : function() {
if(document.get ElementsByTagNa me){
var span=document.g etElementsByTag Name("span");
for(var ii=span.length; ii--;) {
if(span[ii].className.inde xOf(MARKER_CLAS S)!=-1) {
createSelection FromNode(span[ii]);
break;
}
}
}
}
};
})();

function submitHandler(f rm){
frm.elements['SelectionInfo'].value=
SelectionManage r.markLastSelec tion()?document .body.innerHTML :"";
return true;
}

window.onload = function(evt){
SelectionManage r.highlightSele ction();
}
</script>

<div>Hello, World!</div>

<form action="foo" onsubmit="retur n submitHandler(t his)">
<input type="hidden" name="Selection Info">
<input type="submit" value="Send selection">
</form>
---
HTH,
Yep.

Jul 23 '05 #6

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

Similar topics

3
6674
by: Noah | last post by:
I have a text field in a form. I want the user to be able to click a DELETE button and have the character at the cursor position deleted. This would be just as if the user had pressed the Back Space key on the keyboard... But this is for a kiosk application with no keyboard :-( so I need to program a delete button. I have code that lets me insert text at the cursor position. And I can move the ABSOLUTE cursor position from the start and...
9
12589
by: MSUTech | last post by:
Hello, What is the best way to check each character within a string? For doing something like encryption, where you check character 1 and replace it with a different character.. then check character 2 and replace it with a different character.... etc.... until completing the string? thanks....
1
2214
by: Colin Green | last post by:
OK here's is what I wish to do. I have an XML file that I want to read into an XmlDocument. I then want to be able to interrogate the XmlNodes to find both their start AND end character positions within the original file. So e.g. <tagA><tagB>sometext</tagB></tagA> ^ ^ ^ ^ ^ ^ 0 6 12 19 26 33
1
10149
by: King Kong | last post by:
we are facing this kind of error when we double click the infragistic web grid please help me on this Regards Moid Iqbal Server Error in '/NetworkAccess' Application. ---------------------------------------------------------------------------- ----
5
11647
by: Just D | last post by:
All, Any valuable idea about subj: "The '%' character, hexadecimal value 0x25" ? I tried to google, but nothing interesting was found. Is it IIS settings problem, user side problem or whatever? We receive it regularly and I guess the problem is not in our source codes. Please help! Just D.
7
5693
by: =?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7z | last post by:
Who could explain the follow issue ? ¦¤ Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'gbk' codec can't encode character u'\x80' in position 0: il legal multibyte sequence or I just put the unicode number
2
3070
by: thuythu | last post by:
Please help me.... I used and Javascript to view the data. But when i click button open a popup windows, then select data and click save button. The popup close and return the main page, but the textbox value in the main page is undefined ---------------------------------------- here are code main page: ------------------------------------------- <script language="JavaScript"> var thedata; var newwin; var thenumber; function...
3
2513
by: magix | last post by:
How can I search for occurance of a character in certain position of a string I checked function strchr, but doesn't option to specify position. Thanks. Regards, Magix
5
6069
by: Andrus | last post by:
I use Winforms RichTextBox control to edit scripts. Scripts are plain ascii texts. When error occurs, script engine returns character position of error in code as integer. How to position cursor to this character position ? RichTextBox does not have current position property. Andrus.
0
8238
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8174
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8336
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7164
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5565
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2607
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 we have to send another system
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.