return character position on page?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jen_designs@hotmail.com

    #1

    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?

  • Yann-Erwan Perio

    #2
    Re: return character position on page?

    jen_designs@hot mail.com wrote:
    [color=blue]
    > 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.[/color]

    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.

    Comment

    • jen_designs@hotmail.com

      #3
      Re: return character position on page?

      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.

      Comment

      • Lee

        #4
        Re: return character position on page?

        jen_designs@hot mail.com said:[color=blue]
        >
        >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.[/color]

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

        Comment

        • Danny

          #5
          Re: return character position on page?


          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, <jen_designs@ho tmail.com> wrote:
          [color=blue]
          > 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?
          >[/color]



          --
          Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

          Comment

          • Yep

            #6
            Re: return character position on page?

            jen_designs@hot mail.com wrote:

            Hi,
            [color=blue]
            > 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.[/color]

            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.

            Comment

            Working...