Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding closest anchor href via scrollOffset

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];
like image 402
Oh Danny Boy Avatar asked May 17 '12 19:05

Oh Danny Boy


2 Answers

Phew! I finished!

JS :

var x=0,y=0;//Here are the given X and Y, you can change them
var idClosest;//Id of the nearest anchor
var smallestIndex;
var couplesXY=[];
var allAnchors;
var html=document.getElementsByTagName("html")[0];
html.style.width="3000px";//You can change 3000, it's to make the possibility of horizontal scroll
html.style.height="3000px";//Here too

function random(min,max)
{
    var nb=min+(max+1-min)*Math.random();
    return Math.floor(nb);
}
function left(obj)//A remixed function of this site http://www.quirksmode.org/js/findpos.html
{
    if(obj.style.position=="absolute")return parseInt(obj.style.left);
    var posX=0;
    if(!obj.offsetParent)return;
    do posX+=obj.offsetLeft;
    while(obj=obj.offsetParent);
    return posX;
}
function top(obj)
{
    if(obj.style.position=="absolute")return parseInt(obj.style.top);
    var posY=0;
    if(!obj.offsetParent)return;
    do posY+=obj.offsetTop;
    while(obj=obj.offsetParent);
    return posY;
}

function generateRandomAnchors()//Just for the exemple, you can delete the function if you have already anchors
{
    for(var a=0;a<50;a++)//You can change 50
    {
        var anchor=document.createElement("a");
        anchor.style.position="absolute";
        anchor.style.width=random(0,100)+"px";//You can change 100
        anchor.style.height=random(0,100)+"px";//You can change 100
        anchor.style.left=random(0,3000-parseInt(anchor.style.width))+"px";//If you changed 3000 from
        anchor.style.top=random(0,3000-parseInt(anchor.style.height))+"px";//the top, change it here
        anchor.style.backgroundColor="black";
        anchor.id="Anchor"+a;
        document.body.appendChild(anchor);
    }
}
function getAllAnchors()
{
    allAnchors=document.getElementsByTagName("a");
    for(var a=0;a<allAnchors.length;a++)
    {
        couplesXY[a]=[];
        couplesXY[a][0]=left(allAnchors[a]);
        couplesXY[a][1]=top(allAnchors[a]);
    }
}
function findClosestAnchor()
{
    var distances=[];
    for(var a=0;a<couplesXY.length;a++)distances.push(Math.pow((x-couplesXY[a][0]),2)+Math.pow((y-couplesXY[a][1]),2));//Math formula to get the distance from A to B (http://euler.ac-versailles.fr/baseeuler/lexique/notion.jsp?id=122). I removed the square root not to slow down the calculations
    var smallest=distances[0];
    smallestIndex=0;
    for(var a=1;a<distances.length;a++)if(smallest>distances[a])
    {
        smallest=distances[a];
        smallestIndex=a;
    }
    idClosest=allAnchors[smallestIndex].id;
    alert(idClosest);
}
function jumpToIt()
{
    window.scrollTo(couplesXY[smallestIndex][0],couplesXY[smallestIndex][1]);
    allAnchors[smallestIndex].style.backgroundColor="red";//Color it to see it
}

generateRandomAnchors();
getAllAnchors();
findClosestAnchor();
jumpToIt();

Fiddle : http://jsfiddle.net/W8LBs/2

PS : If you open this fiddle on a smartphone, it doesn't work (I don't know why) but if you copy this code in a sample on a smartphone, it works (but you must specify the <html> and the <body> section).

like image 27
Mageek Avatar answered Nov 06 '22 12:11

Mageek


[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];
}
like image 107
16 revs Avatar answered Nov 06 '22 12:11

16 revs