Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7989265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T12:42:24+00:00 2026-06-04T12:42:24+00:00

I have a UIWebView with an HTML page completely loaded. The UIWebView has a

  • 0

I have a UIWebView with an HTML page completely loaded. The UIWebView has a frame of 320 x 480 and scrolls horizontally. I can get the current offset a user is currently at. I would like to find the closest anchor using the XY offset so I can “jump to” that anchors position. Is this at all possible? Can someone point me to a resource in Javascript for doing this?

<a id="p-1">Text Text Text Text Text Text Text Text Text<a id="p-2">Text Text Text Text Text Text Text Text Text ... 

Update

My super sad JS code:

function posForElement(e)
{
    var totalOffsetY = 0;

    do
    {
        totalOffsetY += e.offsetTop;
    } while(e = e.offsetParent)

    return totalOffsetY;
}

function getClosestAnchor(locationX, locationY)
{
    var a = document.getElementsByTagName('a');

    var currentAnchor;
    for (var idx = 0; idx < a.length; ++idx)
    {
        if(a[idx].getAttribute('id') && a[idx+1])
        {
            if(posForElement(a[idx]) <= locationX && locationX <= posForElement(a[idx+1])) 
            {
                currentAnchor = a[idx];
                break;
            }
            else
            {
                currentAnchor = a[0];
            }
        }
    }

    return currentAnchor.getAttribute('id');
}

Objective-C

float pageOffset = 320.0f;

NSString *path = [[NSBundle mainBundle] pathForResource:@"GetAnchorPos" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsCode];

NSString *execute = [NSString stringWithFormat:@"getClosestAnchor('%f', '0')", pageOffset];
NSString *anchorID = [webView stringByEvaluatingJavaScriptFromString:execute];
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T12:42:28+00:00Added an answer on June 4, 2026 at 12:42 pm

    [UPDATE] I rewrote the code to match all the anchors that have an id, and simplified the comparison of the norm of the vectors in my sortByDistance function.

    Check my attempt on jsFiddle (the previous one was here ).

    The javascript part :

    // findPos : courtesy of @ppk - see http://www.quirksmode.org/js/findpos.html
    var findPos = function(obj) {
        var curleft = 0,
            curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            while ((obj = obj.offsetParent)) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
        }
        return [curleft, curtop];
    };
    
    var findClosestAnchor = function (anchors) {
    
        var sortByDistance = function(element1, element2) {
    
            var pos1 = findPos( element1 ),
                pos2 = findPos( element2 );
    
            // vect1 & vect2 represent 2d vectors going from the top left extremity of each element to the point positionned at the scrolled offset of the window
            var vect1 = [
                    window.scrollX - pos1[0],
                    window.scrollY - pos1[1]
                ],
                vect2 = [
                    window.scrollX - pos2[0],
                    window.scrollY - pos2[1]
                ];
    
            // we compare the length of the vectors using only the sum of their components squared
            // no need to find the magnitude of each (this was inspired by Mageek’s answer)
            var sqDist1 = vect1[0] * vect1[0] + vect1[1] * vect1[1],
                sqDist2 = vect2[0] * vect2[0] + vect2[1] * vect2[1];
    
            if ( sqDist1 <  sqDist2 ) return -1;
            else if ( sqDist1 >  sqDist2 ) return 1;
            else return 0;
        };
    
        // Convert the nodelist to an array, then returns the first item of the elements sorted by distance
        return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
    };
    

    You can retrieve and cache the anchors like so when the dom is ready : var anchors = document.body.querySelectorAll('a[id]');

    I’ve not tested it on a smartphone yet but I don’t see any reasons why it wouldn’t work.
    Here is why I used the var foo = function() {}; form (more javascript patterns).

    The return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0]; line is actually a bit tricky.

    document.body.querySelectorAll('a['id']') returns me a NodeList with all the anchors that have the attribute “id” in the body of the current page.
    Sadly, a NodeList object does not have a “sort” method, and it is not possible to use the sort method of the Array prototype, as it is with some other methods, such as filter or map (NodeList.prototype.sort = Array.prototype.sort would have been really nice).

    This article explains better that I could why I used Array.prototype.slice.call to turn my NodeList into an array.

    And finally, I used the Array.prototype.sort method (along with a custom sortByDistance function) to compare each element of the NodeList with each other, and I only return the first item, which is the closest one.

    To find the position of the elements that use fixed positionning, it is possible to use this updated version of findPos : http://www.greywyvern.com/?post=331.

    My answer may not be the more efficient (drdigit’s must be more than mine) but I preferred simplicity over efficiency, and I think it’s the easiest one to maintain.

    [YET ANOTHER UPDATE]

    Here is a heavily modified version of findPos that works with webkit css columns (with no gaps):

    // Also adapted from PPK - this guy is everywhere ! - check http://www.quirksmode.org/dom/getstyles.html
    var getStyle = function(el,styleProp)
    {
        if (el.currentStyle)
            var y = el.currentStyle[styleProp];
        else if (window.getComputedStyle)
            var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
        return y;
    }
    
    // findPos : original by @ppk - see http://www.quirksmode.org/js/findpos.html
    // made recursive and transformed to returns the corect position when css columns are used
    
    var findPos = function( obj, childCoords ) {
       if ( typeof childCoords == 'undefined'  ) {
           childCoords = [0, 0];
       }
    
       var parentColumnWidth,
           parentHeight;
    
       var curleft, curtop;
    
       if( obj.offsetParent && ( parentColumnWidth = parseInt( getStyle( obj.offsetParent, '-webkit-column-width' ) ) ) ) {
           parentHeight = parseInt( getStyle( obj.offsetParent, 'height' ) );
           curtop = obj.offsetTop;
           column = Math.ceil( curtop / parentHeight );
           curleft = ( ( column - 1 ) * parentColumnWidth ) + ( obj.offsetLeft % parentColumnWidth );
           curtop %= parentHeight;
       }
       else {
           curleft = obj.offsetLeft;
           curtop = obj.offsetTop;
       }
    
       curleft += childCoords[0];
       curtop += childCoords[1];
    
       if( obj.offsetParent ) {
           var coords = findPos( obj.offsetParent, [curleft, curtop] );
           curleft = coords[0];
           curtop = coords[1];
       }
       return [curleft, curtop];
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a UIWebView which loads an HTML page which has some links to
I have a uiwebview that sends its loaded page url to a uitableview to
i am having a UIWebView showing and HTML page that has some checkboxes, radio
I have an app with UIWebView which loads a remote HTML page...Now on this
I have simple UIWebView with loaded html. i want to save the javascript range
I have simple UIWebView with loaded html. I want to show the PopoverView pointed
I have a UIWebView containing html-formatted text. In the text some words are links.
I have a piece of HTML which I am displaying inside a UIWebView using
I have a simple app with a full screen UIWebView. This contains HTML generated
I'm experimenting playing video in a UIWebView. If I have some html like this:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.